当前位置: 动力学知识库 > 问答 > 编程问答 >

backbone.js - Binding a model to a backbone client template

问题描述:

I have the following backbone.js client side template:

<script id="calleeTemplate" type="text/x-jquery-tmpl">

<tr style="background-color: ${StatusColour}">

<td class="responder">${ContactFullName}</td>

<td class="status" style="width:200px">${Status}</td>

<td class="replied">${Replied}</td>

<td class="wauto">${Response}</td>

</tr>

</script>

In order to be able to bind to these properties, I have the following render method of a view:

App.Views.Callees = Backbone.View.extend({

initialize: function () {

},

el: $('#calleesStatuses'),

render: function () {

var col = _.map(this.collection.models, function (item) {

return item.attributes;

});

$('#calleesStatuses').html('');

$('#calleeTemplate').tmpl(col).appendTo(this.el);

}

});

I have to extract the attributes using the underscore _.map function from the model. I think the reason for this is because backbone uses the .get("property") to extract the property value.

This does not seem right to me, am I doing anything wrong?

网友答案:

You're right, you have to transform the data in order to be able to easily use it with tmpl.

However, it's better practice to use toJSON rather than accessing attributes directly. It's probably best to avoid calling the .models directly as well.

You don't need to anyway, backbone collections have a full suite of underscore.js enumerators. So you can cut your transformation down to one line:

var col = this.collection.invoke('toJSON')
分享给朋友:
您可能感兴趣的文章:
随机阅读: