如何在backbone.js中处理视图之外的对象事件?
正如在骨干待办事项示例中一样,我有一个元素集合。我制作了 2 个视图,一个用于列表,一个用于每个元素。效果很好。
但是,由于我需要修改列表的元素,在元素视图中,我处理修改事件使用 colorbox 插件,其中包含 html 表单。 html 是动态创建的并传递给 colorbox 元素。
我使用 colorbox 和骨干形式的附加插件。
现在:在我看来,弹出窗口不是子项(在 DOM 中),所以我不知道如何在“按钮提交”操作上触发事件。
以下是代码片段(省略了无用部分):
// ** view of the single collection element
window.listElement = Backbone.View.extend({
tagName: 'li',
[...]
updateElement:function(){
//creates the update form in a popup menu
var form=new Backbone.Form({BLA BLA BLA...I TESTED IT, IT WORKS.
}).render();
$(form.el).append('<input id="update-btn" type="button" name="updateBtn" value="Update" style="display: block;">');
self=this;
//HERE COME THE TROUBLES
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
}).delegate('#update-btn','click',self.saveEl());
},
saveEl:function(){
console.log("now saving..")},
},
发生的情况是,打开弹出窗口时会触发 saveEl 方法(或函数?,哪个术语更正确?)。
我还尝试了不同版本的代码:
initialize: function(){//added this in the initialize function
_.bindAll(this, "saveEl");
$('#update-btn').bind('click', this.saveEl());
},
updateElement:function(){
//LIKE BEFORE BUT WITHOUT DELEGATE FUNCTION
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
});
},
saveEl:function(){
console.log("now saving..")},
},
在第二种情况下,创建视图时调用 saveEl 函数(因此列表中的每个元素都会调用一次)。
我知道我可以为弹出窗口创建一个视图,但有些东西告诉我它太复杂了,我应该有一个更简单的架构。
事实上,这个问题更普遍:是否可以处理 $(this.el) 范围之外的 DOM 对象触发的事件而不为它们创建视图?
提前致谢。
-----------------更新:--------------
工作代码的最终版本如下:
// ** view of the single collection element
window.listElement = Backbone.View.extend({
tagName: 'li',
[...]
updateElement:function(){
//creates the update form in a popup menu
var form=new Backbone.Form({BLA BLA BLA...I TESTED IT, IT WORKS.
}).render();
$(form.el).append('<input id="update-btn" type="button" name="updateBtn" value="Update" style="display: block;">');
$(form.el).delegate('#update-btn','click',this.saveEl())
$.colorbox({
html:form.el,
[...] /SOME OTHER PARAMS
});
},
saveEl:function(){
console.log("now saving..")},
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
$.colorbox 不会发回正确的 html 来绑定它。
正如你所看到的,你给了 colorbox
form.el
,所以你可以直接绑定form.el
:你应该使用
on
现在因为delegate
是一种旧方法: http://api.jquery.com/on /--------------------------------
是的,你可以处理视图范围之外的 DOM 对象触发的事件,你只需要使用
$('#your-element')
代替this.$('#your-element' )
。对于您的代码,直接触发
saveEl
是正常的,因为您将函数的结果赋予delegate
,您需要提供函数的指针,如下所示:EDIT:
$.colorbox doesn't send back the right html to bind it.
As you can see, you give to colorbox
form.el
, so you can directly bindform.el
:You should use
on
now becausedelegate
is an old method: http://api.jquery.com/on/----------------------
Yes, you can handle events fired by DOM object outside the scope of the view, you just need to use
$('#your-element')
insteadthis.$('#your-element')
.For your code, it's normal to trigger
saveEl
directly because you give todelegate
the result of that function, you need to give the pointer of the function like this: