正如在主干-todolist 示例中一样,我有一个元素集合。我制作了 2 个视图,一个用于列表,一个用于每个元素。它工作得很好。
但是,由于我需要修改列表的元素,因此在元素视图中,我处理修改事件,使用包含 html 表单的colorbox 插件打开一个弹出窗口。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..")},
}
});