我尝试开始使用backbone.js,但我发现当我不使用“body”作为视图的el时,该事件不起作用。
这是代码。您可以将其另存为 html 文件并运行。
<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 将事件处理程序绑定到视图的this.el
使用委托形式on http://api.jquery.com/on/ (or delegate http://api.jquery.com/delegate/在较旧的 Backbones 中),请参阅Backbone.View#delegateEvents http://backbonejs.org/#View-delegateEvents了解详情。因此,如果您想要这些活动:
events: {
'click button#openEssay':'openEssay'
}
然后做任何事this.$el.find('button#openEssay')
需要匹配某些东西(其中this
当然是视图对象)。您的四次尝试中只有一次:
el: 'body'
el:'#div'
tagName: 'li'
id: 'div'
会放<button id="openEssay">
inside this.el
所以只有(1)将会通知openEssay
当你按下按钮时。如果你把按钮放在里面#div
then (2)也会起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)