I tried to start to work with backbone.js, but I found the Event does not work when I do NOT use ‘body’ as the View’s el.
Here is the code. You can save it as a html file and run it.
<html>
<body>
<button id='openEssay'>test</button>
<div id='div' style='width:100px;height:100px;'></div><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script><script>
(function($){
var AppView = Backbone.View.extend({
el:'body',//success
//fail el:'#div',
//fail tagName: 'li',
//fail id:'div',
initialize:function(){
_.bindAll(this, 'openEssay');
},
events:{
'click button#openEssay':'openEssay'
},
openEssay:function(){
alert('a');
}
});
var app = new AppView();
})(jQuery);
</script>
</body>
</html>
Backbone binds the event handlers to the view’s
this.elusing the delegation form ofon(ordelegatein older Backbones), seeBackbone.View#delegateEventsfor details. So if you want these events:to do anything then
this.$el.find('button#openEssay')needs to match something (wherethisis, of course, the view object). Only one of your four attempts:el: 'body'el:'#div'tagName: 'li'id: 'div'will put
<button id="openEssay">insidethis.elso only (1) will callopenEssaywhen you hit the button. If you put your button inside#divthen (2) would also work.