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?
Backbone. js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it.
BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.
(function () {}).call(this);
is just a way to immediately invoke an anonymous function while specifying a receiver. It works basically this same way as:
this.method = function () {};
this.method();
$(function () {})
, at least in jQuery, is shorthand for
$(document).ready(function () {})
which runs the given function when the DOM tree has been fully constructed. It seems like this is the necessary condition for your Backbone.View.extend
function to work properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With