我知道如何使用偵聽器從我的視圖中過濾集合,但我無法弄清楚如何使用骨幹路由器和url來做到這一點。骨幹路由器不能通信和發送url參數來查看
我無法從路由器訪問我的視圖或集合,因爲它們尚未實例化。我的意思是我不能只是添加一個過濾器方法到我的集合,然後調用app.PurchaseList.filter。我可以創建一個包含已過濾項目的新集合,但是如何將此集合傳遞給我的視圖?
一些問題使用PubSub解答,但我認爲會有更直接的方法。或者,最好不要將url路由用於這樣的任務,並直接從我的視圖中觸發事件(在這種情況下,整個過濾器代碼可以保留在我的AppView視圖中,使事情變得更容易)。
是的,我是初學者,這麼多應該是顯而易見的;)
JS /路由/ 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 /收藏/ purchases.js
var app = app || {};
app.PurchaseList = Backbone.Collection.extend({
model: PurchaseItem,
url: 'api/purchase',
});
*「我無法從路由器訪問我的視圖或集合,因爲它們尚未實例化」*,然後您正在從路由器執行'app.appView.filter('reset');'。這不是一個觀點..?一般來說,我們根據來自路由器的路由初始化事物並傳入url參數...如果您無法訪問任何內容,可能應該考慮重新設計..? –
對不起,這是一個剩餘的函數調用,沒有工作(過濾器未定義),從我實驗時。 – Vey