Khepin..
15
我真的想要做同样的事情,只是找到了我的方式!
试图建立一个todo列表示例,我已经在页面上有一些待办事项,想要将它们作为我的Todos集合中的模型,并使它们的管理方式与添加到空白页面的元素相同.
重要的部分是如何实例化集合.基本上:
你通过jQuery获得现有的html元素.如果模型的视图基于tagName:'li',那么这是您需要在此处检索的标记类型.
您遍历这些标记以刮取构成模型的数据并创建模型
您为每个模型创建一个视图,并将模型和基本元素传递给它.这就是我遇到的问题:我正在创建视图,然后尝试通过my_view.el = xxx添加它.这不起作用.
您将模型添加到集合中
注意:该集合通常与视图绑定,以便使用collection.add也可以更新视图.由于在构造函数中调用了initialize,因此该集合尚未绑定,并且您不会通过在此处添加元素来复制HTML中的元素.
// this is the important part for initializing from html!
khepin.Todos = Backbone.Collection.extend({
model: khepin.Todo,
// In this function we populate the list with existing html elements
initialize: function() {
_.each(
// get all the
todo items (the base for the todo view)// and for each of them:
$('.todo'),
function(a){
// Create the model
var todo = new khepin.Todo();
// Find the todo's text
var task = $(a).find('span')[0];
task = $(task).text();
// set the model correctly
todo.set({
task: task
});
// create the todo view
var todoView = new khepin.TodoView({
model: todo,
el: a // the el has to be set here. I first tried calling new TodoView and setting the 'el' afterwards
// and the view wasn't managed properly. We set the "el' to be the
we got from jQuery});
// Add this new model to the collection
this.add(todo);
},
this
);
}
})
希望这可以帮助!