In my backbone.marionette app, I am trying to set a model attribute 'rank' as it's loop index. here is the code of my collection:

 AngryCats = Backbone.Collection.extend({
          model:AngryCat,
          initialize: function(cats){
              var rank = 1;
              _.each(cats, function(cat){
                    cat.set('rank', rank);
                  rank++;
              })
          }
      });

But I am getting error as :

TypeError: cat.set is not a function
cat.set('rank', rank);

any one tell me what is wrong here? ( please check the fiddle link for complete coding )

Live Demo

有帮助吗?

解决方案

You are passing array of javascript objects. But the set is only available in Backbone.Model instance. Only after initialisation, every single object converted into Backbone.Model Object.

You have to do like

 var rank = 1;
 _.each(cats, function(cat){
     cat.rank = rank;
     rank++;
  })
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top