Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  129] [ 6]  / answers: 1 / hits: 15119  / 12 Years ago, mon, august 20, 2012, 12:00:00

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>

More From » backbone.js

 Answers
29

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:




  1. el: 'body'

  2. el:'#div'

  3. tagName: 'li'

  4. 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.


[#83539] Friday, August 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nicole

Total Points: 648
Total Questions: 95
Total Answers: 103

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
;