cli*_*oid 22 javascript backbone.js underscore.js underscore.js-templating
好的,所以我有这个密钥对值数组,我用作我的模型:
var acs = [{'label':'input box'},{'label':'text area'}];
Run Code Online (Sandbox Code Playgroud)
其余代码如下
var Action = Backbone.Model.extend({});
var action = new Action(acs);
var ActionView = Backbone.View.extend({
tagName:"li",
template: _.template($('#actions-template').html()),
events:{
"click":"makeInput"
},
render:function(){
$(this.el).html(this.template(this.model.toJSON()));
$(".hero-unit>ul").append(this.el);
return this;
},
makeInput:function(){
alert("im in");
}
});
var actionView = new ActionView({model:action});
actionView.render();
Run Code Online (Sandbox Code Playgroud)
问题是关于这个观点.如果这是我想要的视图,我如何遍历我传递的模型
<script type="text/template" id="actions-template">
<% _.each(action, function(acs) { %>
<a class="btn"><%= label %></a>
<% }); %>
</script>
Run Code Online (Sandbox Code Playgroud)
我认为我的观点和循环有问题.有线索吗?谢谢!
mu *_*ort 28
你可能想要做两件事:
调整您提供给模板的数据:
$(this.el).html(this.template({
action: this.model.toJSON()
}));
Run Code Online (Sandbox Code Playgroud)调整模板的内部部分以使用acs.label
而不是label
:
<a class="btn"><%= acs.label %></a>
Run Code Online (Sandbox Code Playgroud)演示:http://jsfiddle.net/ambiguous/xczBy/
第二个想法,我认为你应该使用集合而不是单个模型.你想要添加这个:
var ActionCollection = Backbone.Collection.extend({
model: Action
});
Run Code Online (Sandbox Code Playgroud)
然后调整render
使用this.collection
:
$(this.el).html(this.template({
actions: this.collection.toJSON()
}));
Run Code Online (Sandbox Code Playgroud)
然后开始这样的事情:
var actions = new ActionCollection(acs);
var actionView = new ActionView({collection: actions});
Run Code Online (Sandbox Code Playgroud)
最后,参考actions
模板:
<% _.each(actions, function(acs) { %>
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/6VeXk/
这将更好地匹配Backbone的基于键/值的模型.