[英]backbone.js events and el
Okay, so I've read several other questions regarding Backbone views and events not being fired, however I'm still not getting it sadly. 好的,所以我已经阅读了几个关于Backbone视图和未被触发的事件的其他问题,但是我仍然没有忘记它。 I been messing with Backbone for about a day, so I'm sure I'm missing something basic. 我一直在乱用Backbone大约一天,所以我肯定我错过了一些基本的东西。 Here's a jsfiddle with what I'm working with: http://jsfiddle.net/siyegen/e7sNN/3/ 这是我正在使用的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. GridView上的okay
事件不会触发,我假设因为事件第一次绑定时div.grid-view
不存在。 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) (另外,这是一个简短的例子,但如果我做其他任何我不应该做的事情,请随意对我大喊大叫)
Your problem is that the events on GridView: 你的问题是GridView上的事件:
events: {
'click .grid-view': 'okay'
}
say: 说:
when you click on a descendent that 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">
. 因此.grid-view
元素必须包含在GridView的this.el
而你的this.el
是<div class="grid-view">
。 If you change your events
to this: 如果您将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/ 固定小提琴: http : //jsfiddle.net/ambiguous/5dhDW/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.