[英]Backbone event handler doesn't work
我有两个视图——一个布局视图,它是顶级的,一个新的表单视图,它充当布局的子视图并在其中呈现。 我在表单视图中有一个事件处理程序,它应该根据输入的数据创建我的模型的一个新实例。
这是布局视图:
var LayoutView = Backbone.View.extend({
el: "#layout",
render: function (view) {
this.child = view;
if (this.child) {
this.child.remove();
}
this.$el.html(this.child.render().el);
return this;
}
});
这是我的表单视图:
var ResumeForm = Backbone.View.extend({
events: {
'click #create': 'createResume'
},
initialize: function () {
this.template = _.template($('#new-resume').html());
},
render: function () {
this.$el.html(this.template());
return this;
},
createResume: function () {
// getting values from template inputs and saving them to model
var resume = new Resume({
profession: $('#profession').val(),
firstName: $('#firstname').val(),
lastName: $('#lastname').val()
});
// saving a new model to collection instance
resumes.add(resume);
resume.save(null, {
success: function (res) {
console.log("POST resume id " + res.toJSON().id);
},
error: function () {
console.log("Failed to POST");
}
});
}
});
我的表单视图完美地呈现在我的布局视图中,但是当我输入值并单击#create
按钮时,没有任何反应——既不保存模型,也不记录我的createResume
方法中的任何错误错误。 我怀疑在布局视图中渲染表单视图时,这行this.$el.html(this.child.render().el);
只是销毁所有事件侦听器,因为如果我将这些侦听器添加到布局视图中,它就可以工作。
有什么方法可以解决这个问题吗?
Backbone 的视图remove
函数取消委托绑定到el
的事件。
从带注释的来源:
remove: function() { this._removeElement(); this.stopListening(); return this; }, _removeElement: function() { this.$el.remove(); },
这与 jQuery .remove()
函数有关(重点是我的):
与
.empty()
类似,.remove()
方法从 DOM 中取出元素。 当您想要删除元素本身以及其中的所有内容时,请使用.remove()
。 除了元素本身之外,所有与元素关联的绑定事件和 jQuery 数据都将被删除。 要在不删除数据和事件的情况下删除元素,请改用.detach()
。
如果在重用视图之前调用remove
,则需要手动调用this.delegateEvents()
以重新绑定events
哈希中的events
并重新连接视图通过this.listenTo(...)
侦听的任何事件。
但是重用视图的最佳方法是,无需调用remove
调用stopListening
,您可以使用setElement
取消委托事件,并将视图元素更改为传递的元素,然后重新委托事件。
setElement: function(element) { this.undelegateEvents(); this._setElement(element); this.delegateEvents(); return this; },
你的LayoutView
会变成这样:
var LayoutView = Backbone.View.extend({
el: "#layout",
render: function(view) {
// if the view is different, make sure to undelegate the old view.
if (this.child && this.child !== view) this.child.undelegateEvents();
this.child = view;
this.child.setElement(this.$el).render();
return this;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.