鈍足ランナーのIT日記

走るのが好きな5流のITエンジニアのブログ。

趣味の範囲は広いけど、どれも中途半端なクソブロガー楽しめるWebアプリを作ってあっと言わせたい。サーバーサイドPerl(Mojolicious)、クライアントサイドVue.js。Arduinoにも触手を伸ばす予定。

cannot get the cid of the model while rendering a backbone collection over a template

下のURLと同じところで、見事につまずきました。

http://stackoverflow.com/questions/15298449/cannot-get-the-cid-of-the-model-while-rendering-a-backbone-collection-over-a-tem

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;
    }
});