javascript Backbone.js 事件和 el
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7542756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
backbone.js events and el
提问by siyegen
Okay, so I've read several other questions regarding Backbone views and events not being fired, however I'm still not getting it sadly. I been messing with Backbone for about a day, so I'm sure I'm missing something basic. Here's a jsfiddle with what I'm working with: http://jsfiddle.net/siyegen/e7sNN/3/
好的,所以我已经阅读了其他几个关于 Backbone 视图和事件未被触发的问题,但是我仍然没有感到遗憾。我用 Backbone 搞了大约一天,所以我确定我错过了一些基本的东西。这是我正在使用的 jsfiddle:http: //jsfiddle.net/siyegen/e7sNN/3/
(function($) {
var GridView = Backbone.View.extend({
tagName: 'div',
className: 'grid-view',
initialize: function() {
_.bindAll(this, 'render', 'okay');
},
events: {
'click .grid-view': 'okay'
},
okay: function() {
alert('moo');
},
render: function() {
$(this.el).text('Some Cow');
return this;
}
});
var AppView = Backbone.View.extend({
el: $('body'),
initialize: function() {
_.bindAll(this, 'render', 'buildGrid');
this.render();
},
events: {
'click button#buildGrid': 'buildGrid'
},
render: function() {
$(this.el).append($('<div>').addClass('gridApp'));
$(this.el).append('<button id="buildGrid">Build</button>');
},
buildGrid: function() {
var gridView = new GridView();
this.$('.gridApp').html(gridView.render().el);
}
});
var appView = new AppView();
})(jQuery);
The okay
event on the GridView does not fire, I'm assuming because div.grid-view
does not exist when the event is first bound. How should I handle the binding and firing of an event that's built on a view dynamically? (Also, it's a short example, but feel free to yell at me if I'm doing anything else that I shouldn't)
okay
GridView 上的事件不会触发,我假设是因为div.grid-view
第一次绑定事件时不存在。我应该如何处理动态构建在视图上的事件的绑定和触发?(另外,这是一个简短的例子,但如果我正在做任何我不应该做的事情,请随时对我大喊大叫)
回答by mu is too short
Your problem is that the events on GridView:
您的问题是 GridView 上的事件:
events: {
'click .grid-view': 'okay'
}
say:
说:
when you click on a descendentthat matches
'.grid-view'
, callokay
当您单击匹配的后代时
'.grid-view'
,调用okay
The events are bound with this snippet from backbone.js
:
事件与以下片段backbone.js
绑定:
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
So the .grid-view
element has to be contained within your GridView's this.el
and your this.el
is <div class="grid-view">
. If you change your events
to this:
因此该.grid-view
元素必须包含在您的 GridView 中,this.el
而您this.el
的<div class="grid-view">
. 如果你改成events
这样:
events: {
'click': 'okay'
}
you'll hear your cows (or "hear them in your mind" after reading the alert depending on how crazy this problem has made you).
你会听到你的奶牛的声音(或在阅读警报后“在你的脑海中听到它们”,这取决于这个问题让你有多疯狂)。
Fixed fiddle: http://jsfiddle.net/ambiguous/5dhDW/