Jahirul Islam
Jahirul Islam

Reputation: 436

_.each in BackboneJS

var MenuListView = Backbone.View.extend({
            el : '#menus',
            reset : function() {
                var hIndex = this.getTheMenuIndexHighlighting();
                _.each(this.model.models[hIndex].attributes.subMenus, function(model, index) {
                    model.set({highlight : false});
                });
    });

_.each not rotating in the above code.

UPDATE here is how my submenu json

[ {title:'Applications',bmUrl:'',id:'1',subMenus:[ {title: 'MsWord', bmUrl : 'msword.com';, id: 1, subMenus: null}, {title: 'MsExcel', bmUrl : 'msexcel.com';, id: 2, subMenus: null}, {title: 'MsPP', bmUrl : 'mspp.com';, id: 3, subMenus: null}, {title: 'MsOneNote', bmUrl : 'msonenote.com';, id: 4, subMenus: null}, {title: 'MsOutlook', bmUrl : 'msoutlook.com';, id: 5, subMenus: null} ],imgUrl:''}] 

Can any body tell me why?

Replacing _.each to $.each is rotating the loop but doesn't trigger the appropriate model view updating method.

Upvotes: 0

Views: 900

Answers (2)

Deeptechtons
Deeptechtons

Reputation: 11125

It certainly seems the answer will have to be put by guessing , because you posted a meager amount of code. But here is my try

  • I think this should be this.model.models[hIndex].attributes.subMenus converted to this.collection.models[hIndex].attributes.subMenus assuming this.model refers to a collection which certainly has the models property.

  • Second if you need model at a index there is at method in collection thus simplifying to this.collection.at(hIndex).attributes,subMenus

  • third since we use collection (referring to subMenus) you could do this now this.collection.at(hIndex).get("subMenus").each(function(subMenu){alert(subMenu.toJSON());})

your final code must be ( with loads of assumptions)

var MenuListView = Backbone.View.extend({
    el: '#menus',
    reset: function () {
        var hIndex = this.getTheMenuIndexHighlighting();
        this.collection.at(hIndex).get("subMenus").each(function (subMenu) {
            alert(subMenu.toJSON());
        })
    });

Update

Since you still seem to be noob to BBjs world. Create a view instance like below and you will have the above code work like jiffy

var viewInstance = new MenuListView({collection:Menu})

where Menu is the instance(new) of Collection (which you use)

Upvotes: 0

Parv Sharma
Parv Sharma

Reputation: 12705

you should change this line

this.model.models[hIndex].attributes.subMenus

to

this.model.at(hIndex).get("subMenus")

EDIT:- by saying this i was assuming that subMenus in itself is a collection
but now it appears that its an array and going by the underscore site _.each() isnt available for arrays and only can be used on collections. where as jquerys each can be applied to arrays.

http://documentcloud.github.com/underscore/#arrays
link to underscore website notice that each isnt included for arrays

Upvotes: 2

Related Questions