我已经获得了一大堆启动时加载的任务。
我想根据选定的列表/收件箱显示它们,以便每个列表不会有额外的负载。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'或者应该创建子集合。我刚刚发现你的情况有点类似。你能对此有所了解吗?在此先感谢 –