backbone.js click event not firing
Going through a very basic tutorial on backbone.js views.
The expected behavior is to call the render function when #sayhello button is clicked. Render simply uses jQuery's html method to put "hello Bud Abbot" in el.
But when I click the #sayhello button, nothing happens. No errors or anything. I set a breakpoint in firebug and watch it just skip the render function.
Here's the js:
App = (function($){
jQueryView = Backbone.View.extend({
initialize: function(){
this.el = $(this.el);
}
});
HelloWorldView = jQueryView.extend({
el: $('#helloworld'),
events:{ 'click #sayhello': 'render'
},
initialize: function(params){
jQueryView.prototype.initialize.call(this);
this.name = params.name;
},
render: function(){
console.log("rendering");
this.el.html("hello " + this.name);
}
});
var self = {};
self.start = function(){
new HelloWorldView({name: 'Bud Abbot'});
};
return self;
});
And here's the html:
<div id="helloworld"></div>
<button id="sayhello">Say Hello</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
What seems strange is when I change this:
new HelloWorldView({name: 'Bud Abbot'});
to this:
new HelloWorldView({name: 'Bud Abbot'}).render();
the render method is called, but when I try to do it开发者_开发技巧 with an event - no dice. Any help to understand what I'm doing wrong is greatly appreciated.
It's because #sayhello is not part of your view. Try putting #sayhello inside #helloworld:
<div id="helloworld">
<button id="sayhello">Say Hello</button>
</div>
If you are dynamically rendering the page using the templates, then in the render function consider calling view.setElement(...);
this.setElement($('#login-container'));
精彩评论