I know how to filter a collection from within my view using listeners, but I can't figure out how to do it using the backbone router and the url.
I can't access my views or collections from the router, as they're not instantiated yet. By the I mean I can't just add a filter method to my collection and then call app.PurchaseList.filter. I could create a new collection, containing the filtered items, but how do I relay this to my view?
Some questions were answered using PubSub, but I thought there'd be a more straight forward way. Or is it preferred not to use url routes for such a task and trigger events from my views directly (in that case the entire filter code could stay within my AppView view, making things a lot easier).
And yes, I am a beginner, so much should be obvious ;)
js/routes/backboneRouter.js
var app = app || {};
app.Router = Backbone.Router.extend({
routes: {
'filter/:filter': 'filter'
},
filter: function(filter) {
//...
}
});
js/app.js
var app = app || {};
$(function() {
app.router = new app.Router();
Backbone.history.start();
app.appView = new app.AppView();
});
js/views/appView.js
var app = app || {};
app.AppView = Backbone.View.extend({
el: '#app',
initialize: function() {
this.collection = new PurchaseList();
this.collection.fetch({reset: true});
this.render();
this.listenTo(this.collection, 'add', this.renderPurchases);
this.listenTo(this.collection, 'reset', this.render);
},
events: {
'click #add-purchase': 'addPurchase',
},
filter: function(filter) {
console.log(filter);
},
addPurchase: function(event) {
//...
},
render: function() {
this.collection.each(function(item) {
this.renderPurchases(item);
}, this);
},
renderPurchases: function(item) {
var purchaseView = new PurchaseView({
model: item
});
this.$('#list').append(purchaseView.render().el);
}
});
js/collections/purchases.js
var app = app || {};
app.PurchaseList = Backbone.Collection.extend({
model: PurchaseItem,
url: 'api/purchase',
});
app.appView.filter('reset');from the router.. isn't that a view..? Generally we initialize the things depending on routes from the router and pass in the url params... If you don't have access to anything maybe you should consider redesigning..? - T J