cannot get the cid of the model while rendering a backbone collection over a template
下のURLと同じところで、見事につまずきました。
cidという、Backbone.jsで採番されるIDをテンプレートの中に出力したかった。
・・・
render: function(){
this.$el.html(this.template( {todos : this.collection.toJSON()}));
}
// このままだと、cidがテンプレートに渡らない。
・・・
<script type="text/template" id="todoList_template">
<table>
<tr><th>名前</th><th>店</th><th>量</th><th>値段</th><th>単価</th><th>削除</th></tr>
{{ _(todos).each(function(todo) { }}
<tr><td>{{= todo.name }}</td><td>{{= todo.shop }}</td><td>{{= todo.quantity }}</td><td>{{= todo.price }}</td><td>{{= todo.gratan }}</td><td data-id="{{= todo.cid }}" class="delete">×</td></tr>
{{ }); }}
</table>
</script>
モデルのtoJSONを下記のようにオーバーライドするといいようです。
var Todo = Backbone.Model.extend({ toJSON: function() { var json = Backbone.Model.prototype.toJSON.apply(this, arguments); json.cid = this.cid; return json; } });