[英]backbone.js - events only firing once
My events aren't working as I'd hoped, and I think I know why. 我的活动没有像我希望的那样发挥作用,我想我知道为什么。 When the perpage span is clicked, everything renders correctly.
单击perpage跨度时,所有内容都会正确呈现。 But I realized - maybe the events aren't reattached to the new markup?
但我意识到 - 也许这些事件没有重新附加到新标记上? Could that be why it only works once?
难道这就是它只运作一次的原因吗? (If I click the span with the number 10 in it, 10 items appear like it should be. But afterwards, anything I click doesn't change anything)
(如果我单击其中包含数字10的跨度,则会显示10个项目。但之后,我点击的任何内容都不会改变任何内容)
What's a better way to organize this? 有什么更好的方法来组织这个? Should the template not include the pagination portion?
模板是否应该包含分页部分? How do I attach backbone events to markup after it has rendered again?
如何在再次渲染后将骨干事件附加到标记?
var ListView = Backbone.View.extend({
initialize: function() {
var self = this;
this.collection.bind("refresh", function(){self.render();});
this.render();
},
events: {
'click ul#perpage span': 'setperpage'
},
setperpage: function(event) {
this.collection.perpageurl = '/perpage/' + $(event.target).text();
this.collection.fetch();
this.collection.refresh();
},
render: function() {
template = _.template('\
<table>\
<% _(collection).each(function(model){%>\
<tr><td><%=model.id%></td><td><%=model.name%></td><td><%=model.email%></td></tr>\
<%}); %>\
</table>\
<ul id="perpage">\
<li><span>5</span></li>\
<li><span>10</span></li>\
</ul>\
');
var context = {collection: this.collection.toJSON()};
$(this.el).html(template(context));
$('#app').html(this.el);
return this;
}
});
try: 尝试:
render: function()
{
// …
this.delegateEvents();
return this;
}
For debugging events in JavaScript use Visual Event . 对于JavaScript中的调试事件,请使用Visual Event 。 It will tell you which elements have events attached to them.
它会告诉您哪些元素附加了事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.