我已經獲得了一大堆啓動時加載的任務。
我想根據選定的列表/收件箱顯示它們,以便每個列表不會有額外的負載。Backbone.js - 在視圖中過濾和顯示收集數據的正確方法
window.Task = Backbone.Model.extend({});
window.TasksCollection = Backbone.Collection.extend({
model: Task,
url: '/api/tasks',
inbox: function() {
return this.filter(function(task) {
return task.get('list') == null;
});
},
list: function(id) {
return this.filter(function(task) {
return task.get('list') == id;
});
}
});
window.tasks = new TasksCollection;
window.TaskView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#item-template').html()),
initialize: function() {
_.bindAll(this, 'render', 'close');
this.model.bind('change', this.render);
this.model.view = this;
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.setContent();
return this;
},
});
window.TasksView = Backbone.View.extend({
el: '#todo-list',
collection: tasks,
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('reset', this.render);
this.collection.fetch();
},
render: function() {
var t = this;
$(t.el).html('');
this.collection.each(function(task) {
var view = new TaskView({ model:task });
$(t.el).append(view.render().el);
});
return this;
},
});
window.Nicetask = Backbone.Router.extend({
routes: {
'': 'inbox',
'/inbox': 'inbox',
'/list/:id': 'list',
},
initialize: function() {
_.bindAll(this, 'inbox', 'list');
window.tasksView = new TasksView;
},
inbox: function() {
tasks.reset(tasks.inbox());
},
list: function(id) {
tasks.reset(tasks.list(id));
}
});
此代碼的工作,但reset()
函數從任務收集實際列表中刪除其它任務。而在另一條路線上,任務收集是空的。
是否有任何合理的方法來實現這一目標?謝謝你的任何想法。
PS:新手骨幹
UPDATE
THX到@sled和@ibjhb徵求意見,這裏是工作液的片段。
window.TasksView = Backbone.View.extend({
el: '#todo-list',
collection: Backbone.Collection.extend(),
initialize: function() {
_.bindAll(this, 'render', 'addOne', 'addAll');
this.collection.bind('add', this.addOne);
this.collection.bind('reset', this.render);
},
render: function(data) {
$(this.el).html('');
_.each(data, function(task) {
this.addOne(task);
}, this);
return this;
},
addOne: function(task) {
var view = new TaskView({ model:task });
$(this.el).append(view.render().el);
},
});
window.Nicetask = Backbone.Router.extend({
routes: {
'': 'inbox',
'/inbox': 'inbox',
'/today': 'today',
'/list/:id': 'list',
},
initialize: function() {
_.bindAll(this, 'inbox', 'today');
window.tasksView = new TasksView;
window.menuView = new MenuListView;
tasks.fetch();
},
inbox: function() {
tasksView.render(tasks.inbox());
},
today: function() {
tasksView.render(tasks.today());
},
list: function(id) {
tasksView.render(tasks.list(id));
}
});
拉出我的頭髮一個小時。感謝你的回答! – Chev
使用Backbone Marionette可能嗎?這解決了很多問題。 – Blacksonic
嗨Juraj,我有一個情況,我得到一個JSON樹,我必須創建集合,只有當我們點擊子節點。例如。 Root1> child1> subchild1。在這裏,我必須首先顯示根節點,並且只有在單擊根節點'Root1'時應該顯示子列表'child1'或者應該創建子集合。我剛剛發現你的情況有點類似。你能對此有所瞭解嗎?在此先感謝 –