I just started with backbone.js and is currently making a page which has a div #listing_filter containing text input elements and a table showing some listings fetched from a RESTful backend (PHP/Codeigniter). The values in the text input will act as filters to narrow down the results retrieved by the server.
Problem: Whenever the value in any of the text boxes changes, I want the browser to GET another set of results based on the filter values. Below is my attempt, where the updateFilter function does not fire even though the text input value was changed. Any ideas what went wrong?
Another question will be whether I should put the contents of #listing_filter into a template, or just hardcode it into the main body HTML? Thanks!
JS Code
window.ListingFilterView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'updateFilter');
},
events: {
'change input' : 'updateFilter'
},
updateFilter: function() {
console.log('hey');
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
},
listings: function() {
//... some other code here
this.listingFilterView = new ListingFilterView();
}
});
HTML Code
<div id="listing_filter">
Price: <input type="text" id="listing_filter_price" />
Beds: <input type="text" id="listing_filter_bedroom" />
Baths: <input type="text" id="listing_filter_bathroom" />
</div>
A Backbone view will only respond to events on the view’s
elor on elements that are inside itsel. By default, the view’selis just an empty<div>and you’re not telling the view to use anything else.You can tell the view which
elto use (http://jsfiddle.net/ambiguous/5yXcU/1/):or you can let the view attach itself to that element using
setElement(http://jsfiddle.net/ambiguous/APEfa/1/):or set the
elwhen you define the view (http://jsfiddle.net/ambiguous/nyTZU/):Once that’s out of the way, you’ll need to understand that an
<input>won’t trigger a change event until it loses focus so you’ll have to wait for the user to tab-out of the input or switch to listening forkeypressevents and using a timer to detect when they’ve stopped typing.