I try to create a class with a method and then call this method. But the alert() is never executed. Why??
class Demo
constructor: (text) ->
#text = text
demo: ->
alert #text
d = new Demo "Hallo"
console.log d
d.demo
Functions must be called with parens if there are no arguments.
d.demo should be d.demo().
Related
I have come across this construct a few times.
Example 1:
_ = require 'underscore'
class Controller extends App
_doSomething: _.throttle (event) ->
$div = $(event.target).closest 'div'
...
My Question:
I have trouble understanding why this construct is valid.
Normally a class function definition goes like:
_doSomething: (event) ->
$div = $(event.target).closest 'div'
...
, 500
So how can _.throttle sit in between : and (event) the function parameter?
If _.throttle is supposed to act as an wrapper, shouldn't it be written as
_doSomething = _.throttle( (event) -> # an anonymous function that takes event as parameter
$div = $(event.target).closest 'div'
...
, 500
Things might be clearer if we add the optional parentheses:
class Controller extends App
_doSomething: _.throttle( (event) ->
$div = $(event.target).closest 'div'
...
)
Now we see that _.throttle is function call and it is being given an anonymous function as its single argument. We can break it down a bit more to further clarify what's going on:
f = (event) ->
$div = $(event.target).closest('div')
...
throttled_function = _.throttle(f)
class Controller extends App
_doSomething: throttled_function
_.throttle returns a function so the code you're looking at just just a complicated version of:
class Controller extends App
_doSomething: some_function
which is nothing special. Keep in mind that you can use anonymous functions when building a class's methods but named functions or other expressions which evaluate to functions serve just as well; the syntax is really:
name: expr
where expr is some expression and f(x) (or _.throttle(some_anonymous_function)) is an expression.
I found this example of mixins in coffeescript faq but it seems like it doesn't work.
Am I missing something here?
extend = (obj, mixin) ->
for name, method of mixin
obj[name] = method
include = (klass, mixin) ->
extend klass.prototype, mixin
class Button
onClick: -> alert "click"
class Events
include Button, Events
(new Events).onClick()
# => Uncaught TypeError: Object #<Events> has no method 'onClick'
fiddle
You are missing the fact that onClick is defined on the prototype of Button,
and that you did not set the arguments with the right order in the include function
extend = (obj, mixin) ->
for name, method of mixin
obj[name] = method
include = (klass, mixin) ->
extend klass.prototype, mixin
class Button
onClick: -> alert "click"
class Events
include Events,Button.prototype
(new Events).onClick()
see the "fiddle"
So the mixin snippet works pretty well.
I have a class Child which extends Test. I want to call a function from Test from Child.
I tried this:
class Test
constructor: ->
#i = 'hello world'
f1: -> console.log #i
f2: -> console.log 'hello'
class Child extends Test
run: ->
Test::f1()
hello = new Child()
hello.run()
When I call hello.run(), it calls Test.f1(), but the result is undefined. It's not setting the static variable #i before it's running Test.f1().
If I switch Test::f1() to Test::f2(), it gives me the correct result.
I need to know how should I make Test's constructor run when I create a new Child() so that #i is defined in Test when I run Test::f1() from Child.run().
Thanks! :D
Here's one way of doing it:
class Test
#i: 'hello world'
#f1: -> console.log #i
f2: -> console.log 'hello'
class Child extends Test
run: ->
Test.f1()
hello = new Child()
hello.run()
Notice, the i variable is static, so it doesn't make sense to set it in the constructor. Also, the f1 method is now static as well.
(I'm not an expert with CoffeeScript, so I'm not sure what the :: syntax is needed for.)
The constructor is being run when you create a new instance of Child. The problem is the way that you're invoking f1.
You don't want to say Test::f1(). You can just say #f1(), since Child is a subclass of Test. These are different in a very important way: Test::f1() does not set this, so when that function requests this.i, it finds only undefined, because this is set to Window (or something ridiculous like that in the browser, not sure if you're running this in Node). Saying #f1() is the same as saying Test::f1.call(this). This is one of the nice things that CoffeeScript's class system lets you do.
Finally, a pedantic note: there are no static variables in the code you've written. i, as you've written it, is an instance variable. Static variables look like this:
class Test
#staticVar = 1234
Or like this:
class Test
# ...
Test.staticVar = 1234
Instance variables look like this:
class Test
fn: ->
#instanceVar = 1234
Or like this:
test = new Test()
test.instanceVar = 1234
Or even like this (for the default value of an instance variable shared among all instances):
Test::instanceVar = 1234
In a similar vein:
When I call hello.run(), it calls Test.f1(), but the result is undefined. It's not setting the static variable #i before it's running Test.f1().
You're never calling Test.f1(); you're calling Test::f1(), which is very different. In the code you've written, there is no Test.f1, only Test.prototype.f1.
I started writing coffeescript last week, as I am programming a new Play20 site where coffeescript is the standard. I want to update a getData function in my class every 5 minutes, but the setInterval function does not bind to my class. Only the first time it calls getData, because the 'this' object is still reachable, as the setUpdateInterval() function is called from within the constructor.
But after the first call, the setInterval does not have any connection anymore with the Widget instance, and does not know what the this.getData() function is (and how to reach it).
Does someone know how to do it?
Here is my code:
class Widget
constructor: (#name) ->
this.setUpdateInterval()
getData: ->
console.log "get Data by Ajax"
setUpdateInterval: (widget) ->
setInterval( this.getData(), 3000000 )
Now here some Javascript magic is required. Reference
class Widget
constructor: (#name) ->
this.setUpdateInterval()
getData: ->
console.log "get Data by Ajax"
setUpdateInterval: (widget) ->
callback = #getData.bind(this)
setInterval( callback, 3000000 )
This will work in almost all browsers (guess which one not), so the
function will have to be bound differently. Some coffeescript magic:
callback = => #getData
The problem is that you are executing the function, instead of passing a reference to it.
Now, it sounds like you need to also keep the scope of the instance. do and => can help with that.
setUpdateInterval: (widget) ->
setInterval (do =>
#getData), 3000000
true
compiles to
Widget.prototype.setUpdateInterval = function(widget) {
var _this = this;
setInterval((function() {
return _this.getData;
})(), 3000000);
return true;
};
you will note the code executes a self invoking function, which return a function, that creates a closure around this, locking it into the scope of the callback (as _this)
Also note that you don't need to pass widget to the method (you aren't using it anywhere), and you would invoke this function in your constructor, to set up the interval. Whatever you do, you only want to call this method once. You could just put the contents of the function in your constructor.
Finally, since coffeescript returns the value of the last statement from all functions, I throw a true in there, but that might no be necessary.
This is handy in node as well. It's a varient of Tass's answer.
class Widget
constructor: (#options = {}) ->
#options.interval ?= 1000
#setInterval()
timer: ->
console.log 'do something'
setInterval: ->
cb = #timer.bind #
setInterval cb, #options.interval
w = new Widget()
I come from a C#/Java background which use a class based OO system and I don't get the JavaScript/CoffeeScript prototype OO system yet. I've written a CoffeeScript class below which allows me to display names for contacts according to a system-side preference. I can only get the class to work by making the joinNonEmpty(stringList, joinText) method belong to the prototype and calling it the way I would call a static method in Java/C# land.
Is there a way I can make this method call using this.joinNonEmpty(...)?
Can you shed some light on why I can reference the firstLastRender, lastFirstRender and firstOrNickThenLast methods in the constructor with this. but it doesn't work from those methods when calling the joinNonEmpty helper?
Does this have something to do with how I'm locating the appropriate method via the preference map?
prefs = displayNameFormat: "FirstOrNickThenLast"
class DisplayNameRenderer
constructor: ->
#prefToRenderMap =
FirstLast: this.firstLastRender
LastFirst: this.lastFirstRender
FirstOrNickThenLast: this.firstOrNickThenLast
# Why does this method have to be static (a class method)?
#joinNonEmpty: (stringList, joinText) ->
nonEmptyStrings = []
for s in stringList
nonEmptyStrings.push(s) if s isnt null and s isnt ""
nonEmptyStrings.join(joinText)
firstLastRender: (contact) ->
# TypeError: Object expected.
joinNonEmpty([contact.firstName, contact.lastName], ' ')
lastFirstRender: (contact) ->
# TypeError: Object doesn't support this method or property
this.joinNonEmpty([contact.lastName, contact.firstName], ', ')
firstOrNickThenLast: (contact) ->
# Works correctly.
DisplayNameRenderer.joinNonEmpty([(if contact.nickname isnt null and contact.nickname isnt "" then contact.nickname else contact.firstName), contact.lastName], ' ')
render: (contact) ->
#prefToRenderMap[prefs.displayNameFormat](contact)
contact = firstName: "Jonathan", nickname: "Jonny", lastName: "Appleseed"
dnr = new DisplayNameRenderer()
# => "Jonny Appleseed"
console.log dnr.render(contact)
Thanks for taking the time to answer.
this (AKA #) is determined when the function is called (with exceptions as below). So when you do this:
#prefToRenderMap =
FirstLast: this.firstLastRender
LastFirst: this.lastFirstRender
FirstOrNickThenLast: this.firstOrNickThenLast
You're storing unbound references to the three functions in the #prefToRenderMap instance variable and #prefToRenderMap is itself an object. Then you try to call the methods in your DisplayNameRenderer instance like this:
#prefToRenderMap[prefs.displayNameFormat](contact)
and everything falls apart because the methods are called in the wrong context and # isn't what they're expecting it to be. If prefs is 'FirstOrNickThenLast' then you're effectively doing this:
#prefToRenderMap.FirstOrNickThenLast(contact)
and # (AKA this) will be #prefToRenderMap inside the firstOrNickThenLast method. But, of course, #prefToRenderMap doesn't have any of the methods that you're trying to call so you get various errors.
One solution is to use the fat arrow (=>) to define the methods:
The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot.
So you could have things like this:
joinNonEmpty: (stringList, joinText) ->
#...
firstLastRender: (contact) =>
#joinNonEmpty([contact.firstName, contact.lastName], ' ')
and everything will work out. Here's a stripped down demo that will also show you your this problem:
http://jsfiddle.net/ambiguous/RAPJw/1/
You could also avoid this problem by referring to the methods by their names. Given a method name in a string, m = 'some_method', you can call that method like this o[m]() in both JavaScript and CoffeeScript and the result will be the same as if you said o.some_method(). A better structure would look more like this:
class DisplayNameRenderer
constructor: ->
#prefToRenderMap =
FirstOrNickThenLast: 'firstOrNickThenLast'
joinNonEmpty: (stringList, joinText) ->
#...
firstOrNickThenLast: (contact) ->
#joinNonEmpty([(if contact.nickname isnt null and contact.nickname isnt "" then contact.nickname else contact.firstName), contact.lastName], ' ')
render: (contact) ->
#[#prefToRenderMap['FirstOrNickThenLast']](contact)
Note the change to the structure of #prefToRenderMap and how it is used in render. And a demo of this approach: http://jsfiddle.net/ambiguous/DFYwu/
As an aside, instead of saying ClassName.class_method() inside an instance method, you can use the constructor property instead: #constructor.class_method(). Also, you usually say #method() or #property rather than this.method() and this.property in CoffeeScript.