I’m trying to familiarize myself with CoffeeScript and backbone.js, and I must be missing something.
This CoffeeScript:
MyView = Backbone.View.extend
events: {
"click" : "testHandler"
}
testHandler: ->
console.log "click handled"
return false
view = new MyView {el: $('#test_container')}
view.render()
Generates the following JavaScript:
(function() {
var MyView, view;
MyView = Backbone.View.extend({
events: {
"click": "testHandler"
},
testHandler: function() {
console.log("click handled");
return false;
}
});
view = new MyView({
el: $('#test_container')
});
view.render;
}).call(this);
But the click event does not fire testHandler when I click in test_container.
If I change the output JavaScript to:
$(function() {
var MyView, view;
MyView = Backbone.View.extend({
events: {
"click": "testHandler"
},
testHandler: function() {
console.log("click handled");
return false;
}
});
view = new MyView({
el: $('#test_container')
});
view.render;
});
Removing the call(this) and appending the $, everything works as expected. What am I missing?
is just a way to immediately invoke an anonymous function while specifying a receiver. It works basically this same way as:
$(function () {}), at least in jQuery, is shorthand forwhich runs the given function when the DOM tree has been fully constructed. It seems like this is the necessary condition for your
Backbone.View.extendfunction to work properly.