Backbone.js的事件和埃尔 [英] backbone.js events and el
问题描述
好吧,被解雇的骨干方面的意见和事件没那么我读过一些其他问题,但我仍然没有得到它黯然。我被搞乱骨干大约一天的时间,所以我敢肯定,我失去了一些东西基本。这里是什么我正在使用一个的jsfiddle:
http://jsfiddle.net/siyegen/e7sNN/3/
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/
(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);
的好
在GridView控件事件不火,我假设,因为 div.grid视图
做当第一次绑定的事件不存在。我应该如何处理是建立在动态视图中的一个事件的结合和解雇? (另外,这是一个简单的例子,但如果我做其他任何东西,随时我大喊我不应该)
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)
推荐答案
您的问题是,在GridView控件的事件:
Your problem is that the events on GridView:
events: {
'click .grid-view': 'okay'
}
说:
当你点击一个后代匹配。网格视图
,电话好
when you click on a descendent that matches
'.grid-view'
, callokay
事件绑定这个从 Backbone.js的片段
:
The events are bound with this snippet from backbone.js
:
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
所以 .grid视图
元素已被包含在你的GridView的 this.el
和您的 this.el
是&LT; DIV CLASS =网格视图&GT;
。如果你改变你的事件
来的:
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:
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).
固定小提琴: http://jsfiddle.net/ambiguous/5dhDW/
这篇关于Backbone.js的事件和埃尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!