Backbone.js事件在错误实例上触发
在重新设计应用程序的主要功能时,我第一次使用主干网。目标是使用相同的主干收集/查看代码来管理同一页面上的多个不同列表-功能都是相同的,只是数据发生了变化 到目前为止,我已经取得了成功,但发现了一个我无法解决的问题。当您从表单输入中添加新项时,视图将处理该项并调用集合的add函数,该函数使用ajax保存该项。完成后,集合将调用一个“additem”事件,该事件将触发视图重新渲染 但是,只调用最近加载的视图中的事件。即使我完全更改了事件名称,使它们带有前缀,并且对于每个视图都必须是唯一的,这让我感到困惑 很多代码都被删去了,但下面是有问题的部分。在这个代码示例中,我试图为我们需要的每种列表类型添加事件前缀,但不管它在错误的视图中调用什么事件Backbone.js事件在错误实例上触发,backbone.js,Backbone.js,在重新设计应用程序的主要功能时,我第一次使用主干网。目标是使用相同的主干收集/查看代码来管理同一页面上的多个不同列表-功能都是相同的,只是数据发生了变化 到目前为止,我已经取得了成功,但发现了一个我无法解决的问题。当您从表单输入中添加新项时,视图将处理该项并调用集合的add函数,该函数使用ajax保存该项。完成后,集合将调用一个“additem”事件,该事件将触发视图重新渲染 但是,只调用最近加载的视图中的事件。即使我完全更改了事件名称,使它们带有前缀,并且对于每个视图都必须是唯一的,这让我感到
// A collection is made to manage the data - saves to the server, loads, updates, etc
var ListItems = Backbone.Collection.extend({
initialize: function(models, options) {
this.url = options.url;
this.options = options;
},
/**
* We'll use a custom addItem handler so that we're not triggering
* events or ajax requests on .add(), since .fetch() uses it
*/
addItem: function(obj,ajax_elem){
self_col = this;
$.ajax({
type: 'POST',
url: this.options.add_url,
data: obj,
success: function(resp){
if(resp.success === true){
console.log('collection calls ep ' + self_col.options.ep+':addItem');
Backbone.Collection.prototype.add.call(self_col, {text:obj.text,id:resp.id} );
self_col.trigger(self_col.options.ep+':addItem');
} else {
self_col.trigger(self_col.options.ep+':error', resp.errors);
}
// ... rest of stuff
// View manages rendering the items to the page, etc
ListView = Backbone.View.extend({
initialize: function(){
self = this;
this.ep = self.$el.attr('id');
this.collection.bind(this.ep+":addItem",function(){
console.log('view thinks ep is: ' + self.ep+":addItem");
console.log(self.$el);
self.render();
$(window).trigger('Snowy:ajax:stop', self.$el.find(':submit'));
});
// Load the category list
categoryList = new ListView({
collection: new ListItems( INIT_CATEGORIES, {
ep: 'categories',
// other opts
}),
el: $("#categories")
});
问题是,您使用的是globals。对于
self=this
技巧,您必须使它们成为分配它们的函数的局部变量,以便在当前上下文中创建的任何闭包中捕获变量
而不是
self = this;
做
与self\u col
相同,使self=this
更加不愉快。
var self = this;