I have a backbone collection that dynamically takes the URL to fetch results. I then create a view that has the key-up event to capture key input and refresh the collection from the back-end. I have added a listener to my view for collection change but that is not being triggered on my key-up event even though the collection is getting refreshed.
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()
});