【发布时间】:2015-04-11 05:13:15
【问题描述】:
我有一个骨干集合,它动态地使用 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()
});
【问题讨论】:
-
阿德里安这是上一篇文章给你的后续问题
-
你是如何实例化视图和集合的?
-
var employeesView = new employees.EmployeeListView({ collection: new employees.EmployeesCollection() });这就是我正在做的初始化视图和集合
-
任何帮助家伙,这让我很生气,尽管我的收藏被刷新了,但我的视图没有让事件重新呈现自己。如果我只将监听器放在重置事件上,则视图开始重新渲染,但在这种情况下它会滞后一键。
标签: backbone.js backbone-events backbone.js-collections