trying to figure out how to write the following in CoffeeScript:
var foo = new function()
{
var $this = this;
$("#foo").click( this.clicked );
this.clicked = function()
{
$this.alert( $(this).text() );
};
this.alert = function(message)
{
alert(message);
};
};
Unfortunately I can't figure out for the life of me how in CoffeeScript I access the class pointer, "this" is obviously not context aware and will often just point to the variable passed by the callee. So there's no way for me to write the above script in CoffeeScript.
Any advice? I can't find anything useful in the documentation, you have the @ pointers but they also just use the "this" pointer from the current context, making it useless..
You can add methods directly to @ in the constructor to achieve the same effect:
ReplyDeleteclass C
constructor: ->
$this = @
@clicked = ->
console.log @
$this.alert 'pancakes'
alert: (m) ->
console.log m
c = new C
c.clicked()
c.clicked.call window
Demo: http://jsfiddle.net/ambiguous/Y8ZBe/
You'd usually be able to use a bound method and an "event" argument in situations like this though:
class C
clicked: (ev) =>
@alert(ev.target.value)
alert: (m) ->
console.log m
c = new C
c.clicked(target: { value: 'pancakes' })
c.clicked.call window, target: { value: 'pancakes' }
This sort of thing usually turns up in jQuery (or similar) callbacks and they usually have an event argument which explicitly identifies the target "this" so that you can use bound functions.
Demo: http://jsfiddle.net/ambiguous/LafV2/
CoffeeScript is still javascript. The limitations of this still apply. You can obviously write a straight translation:
ReplyDeletefoo = ->
self = this
@clicked = ->
self.alert $(this).text()
@alert = (message) ->
alert message
$('#foo').click @clicked
Yet you should be using prototypes (even in javascript). With the fat arrow => you can bind the function to it's current context (but then you lose the element reference):
foo = ->
$('#foo').click (e) =>
@clicked(e.target)
foo::clicked = (el) ->
@alert $(el).text()
foo::alert = (message) ->
alert message
Or using the class abstraction (nothing more than prototype usage wrapped up in a prettier package) and jQuery.proxy:
class Foo
constructor: ->
$('#foo').click $.proxy @clicked, this
clicked: (e) ->
@alert $(e.target).text()
alert: (message) ->
alert message
$.proxy @clicked, this could be replaced with @clicked.bind @ on modern browsers/engines (see Function.prototype.bind).