html中加入backbone,Backbone.js - 从现有的html实例化模型/视图

这篇博客探讨了如何使用Backbone.js从现有的HTML页面元素中初始化一个Todo列表应用。作者遇到了在创建视图并设置元素时遇到问题,即无法正确管理视图。解决方案是通过jQuery获取待办事项元素,为每个元素创建模型,然后实例化一个TodoView,将模型和基础元素传递给视图,并将其添加到集合中。这个过程涉及到Backbone的模型、视图和集合的交互,以及如何在初始化时处理已有数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

);

}

})

希望这可以帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值