我有一个骨干集合,动态地获取URL来获取结果。然后,我创建一个具有键入事件的视图,以捕获键输入并从后端刷新集合。我已经为我的视图添加了一个监听器来进行集合更改,但是即使集合正在刷新,也没有在我的键盘事件中触发。
employees.EmployeesCollection = Backbone.Collection.extend({
url: function() {
if(this.searchName)
return serviceUrls.employees_searchByName_url + "/" + this.searchName;
else
return serviceUrls.employees_list_url;
},
searchName: null,
search: function(searchName) {
this.searchName = searchName;
this.fetch({
success: function() {
console.log("Fetched new collection");
},
error: function(collection, response){
console.log("Something went wrong");
}
});
},
parse: function(response, options) {
return response;
}
});
employees.EmployeeListView = Backbone.View.extend({
el: "#employee",
template : _.template($('#employees_tpl').html()),
events : {
"keyup #searchValue": "searchByName"
},
initialize: function(options) {
this.options = options;
this.listenTo(this.collection, 'change', this.render);
},
render: function() {
var that = this;
// Only render the page when we have data
this.collection.fetch().done(function() {
that.$el.html(that.template({
collection: that.collection.toJSON()
}));
});
return this;
},
showResults: function(results){
this.collection = results;
this.render();
},
// Search Employees By Name
searchByName: _.throttle(function(e) {
var searchValue = $("#searchValue").val();
this.collection.search(searchValue);
}, 500)
});
// Create Employees View, passing it a new Collection of Employees
var employeesView = new employees.EmployeeListView({
collection: new employees.EmployeesCollection()
});
答案 0 :(得分:1)
根据文件。 a"改变"更改模型属性时触发事件。我建议在fetch中添加reset:true。并将侦听事件更改为重置。
this.collection.fetch({reset:true,
success:function(){...},
error:function(){...}
})
具体来说,在您的搜索方法中:
search: function(searchName) {
this.searchName = searchName;
this.fetch({
success: function() {
console.log("Fetched new collection");
},
error: function(collection, response){
console.log("Something went wrong");
},
reset:true
});
},
然后在您看来,不要听取更改事件,而是听取重置
this.listenTo(this.collection, 'reset', this.render);