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.el
using the delegation form of on
(or delegate
in older Backbones), see Backbone.View#delegateEvents
for details. So if you want these events:
events: {
'click button#openEssay':'openEssay'
}
to do anything then this.$el.find('button#openEssay')
needs to match something (where this
is, of course, the view object). Only one of your four attempts:
el: 'body'
el:'#div'
tagName: 'li'
id: 'div'
will put <button id="openEssay">
inside this.el
so only (1) will call openEssay
when you hit the button. If you put your button inside #div
then (2) would also work.