[英]Get DOM element from template in backbone view
I am using Backbone.js to display a list of people and their data. 我使用Backbone.js显示人员及其数据的列表。
Every person has it's own <div>
. 每个人都拥有自己的
<div>
。 The div is generated by _.template
and contains <input>
fields to display the person's data so it can be adjusted. div由
_.template
生成,包含<input>
字段以显示人员的数据,因此可以对其进行调整。
There is also a button with class=".save"
. 还有一个
class=".save"
的按钮。 In my view I have a function bound to the click of this button. 在我看来,我有一个绑定此按钮的功能。 I am looking for the best approach to get the values of the
<input>
-tags in the div
belonging to the model. 我正在寻找获得属于模型的
div
<input>
-tags的值的最佳方法。
Here is my approach but I'm wondering if there's a better one. 这是我的方法,但我想知道是否有更好的方法 。 In my template I have dyanmically assigned ID's for the DOM elements based on the ID of the model.
在我的模板中,我基于模型的ID动态地为DOM元素分配了ID。 I use the same logic to find back the element in the view.
我使用相同的逻辑来查找视图中的元素。
TEMPLATE 模板
<input value="<%=name%>" id="name_<%=id%>"/>
<input value="<%=age%>" id="age_<%=id%>"/>
<input value="<%=address%>" id="address_<%=id%>"/>
<button class=".save">Save</button>
VIEW 视图
events:{
"click .save":"savePerson"
},
savePerson: function(){
this.model.set({
name: $("#name" + this.model.id).val(),
address: $("#address_" + this.model.id).val(),
age: $("#age_" + this.model.id).val()
});
this.model.save();
}
If every person is a different view instance with its own template, you can just define the scope of the selector for the view's template : 如果每个人都是具有自己模板的不同视图实例,则只需为视图模板定义选择器的范围 :
TEMPLATE 模板
<form id="<%-id%>">
<input value="<%-name%>" name="name"/>
<input value="<%-age%>" name="age"/>
<input value="<%-address%>" name="address"/>
<button class=".save">Save</button>
</form>
VIEW 视图
events:{
"click .save":"savePerson"
},
savePerson: function(){
this.model.set({
name: this.$("input[name='name']").val(),
age: this.$("input[name='age']").val(),
address: this.$("input[name='address']").val()
});
this.model.save();
}
Otherwise, if you have many persons in the same template/view instance (not nice), just catch the current person's id var personId = this.$("#"+this.model.id)
, to use this personId
inside selectors above. 否则,如果你在同一个模板/视图实例中有很多人(不好),只需捕获当前人的id
var personId = this.$("#"+this.model.id)
,在上面的选择器中使用此personId
。
PS: I use <%-value%>
instead of <%=value%>
to interpolate this value, and have it be HTML-escaped. PS:我使用
<%-value%>
代替<%=value%>
来插入此值,并对其进行HTML转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.