我知道如何使用侦听器从我的视图中过滤集合,但我无法弄清楚如何使用骨干路由器和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