Javascript 听一个集合';s Backbone.js视图中的函数调用
尝试在调用filterMe时嗅出,以便更新视图:Javascript 听一个集合';s Backbone.js视图中的函数调用,javascript,backbone.js,Javascript,Backbone.js,尝试在调用filterMe时嗅出,以便更新视图: var MyCollection = Backbone.Collection.extend({ model: MyModel, url: '/myapi', filterMe: function() { return this.where({tag: "A"}); } }); var MyView = Backbone.View.extend({ el: 'div', initia
var MyCollection = Backbone.Collection.extend({
model: MyModel,
url: '/myapi',
filterMe: function() {
return this.where({tag: "A"});
}
});
var MyView = Backbone.View.extend({
el: 'div',
initialize: function() {
var that = this;
//Anytime I call filterMe, I need to update the view with filtered data
this.listenTo(my_collection, 'filterMe', this.render);
my_collection.fetch({
success: function() {
that.render();
}
});
},
render: function() {
...
}
)};
var my_collection = new MyCollection();
var my_view = new MyView();
需要在执行filterMe时启动渲染功能。有什么想法吗?非常感谢 试试看
filterMe: function() {
this.trigger("filterMe");
return this.where({tag: "A"});
}
您应该在“filterMe”函数中触发一个事件,并在视图中侦听它。 试试这个:
var MyCollection = Backbone.Collection.extend({
model: MyModel,
url: '/myapi',
filterMe: function() {
//trigger a custom event that will be listened in the view
this.trigger('filtered');
return this.where({tag: "A"});
}
});
var MyView = Backbone.View.extend({
el: 'div',
initialize: function() {
var that = this;
//listen to custom event triggered in 'filterme' function
my_collection.on('filtered',$.proxy(this.render, this));
my_collection.fetch({
success: function() {
that.render();
}
});
},
render: function() {
...
}
)};
var my_collection = new MyCollection();
var my_view = new MyView();
我想这就是你想要的。请试试这个,让我知道不要提及。如果有帮助,请+1我的答案;)