0

I recently updated my backbone js file to the newest version and what do you know stuff is breaking - so frustrating. I am instantiating a collection within a view and I'm trying to loop through the collection but it's only outputting the last item in the collection can't figure out why here is my code

 NavView = Backbone.View.extend({  
el : $('ul'), 
initialize: function(){

 _.bindAll(this, 'render');
  this.navCollection = new NavigationCollection([ {name: "home", href: '/home'},{name: "about", href:'/about'},{name: "contact", href: '/contact'}]); 
  this.render();

},

I have tried many ways to render the collection out code below

 render : function() {
  this.navCollection.each(function (item) {
        $(this.el).append("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>");
    }, this);
    return this; // remember this for chaining
  //also tried this method as well

 _.each(this.navCollection.models, function(item){
        //$(this.el).append("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>");
        $("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>").appendTo(this.el);
    },this)
    return this; // remember this for chaining
 },

Either way it's only outputting the last item contact instead of three items see here http://dalydd.com/projects/backbone/backbone.html

var NavigationItem = Backbone.Model.extend({
    defaults: {
        name: '',
        href: '',
        last: false,
        id: ''
    },
    initialize: function() {

    }
});

var NavigationCollection = Backbone.Collection.extend({
    model: NavigationItem,
});

Before it was outputting everything but when I updated backbone to newer version it is only printing out 1 - As always any help is appreciated.

Thanks

nikoshr
  • 32,926
  • 33
  • 91
  • 105
James Daly
  • 1,357
  • 16
  • 26

1 Answers1

2

In your NavigationItem definition, you set the default value for id to an empty string :

var NavigationItem = Backbone.Model.extend({
    defaults: {
        name: '',
        href: '',
        last: false,
        id: ''
    }
});

In Backbone 0.9.9, models are added in reverse order and duplicate models are rejected, an empty string being accepted as a valid id, leaving you with your last model in your collection. Remove the default value for id to solve your problem

var NavigationItem = Backbone.Model.extend({
    defaults: {
        name: '',
        href: '',
        last: false
    }
});
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • thanks nikoshr - I would have never of figured that on my own - I thought I was doing the loop incorrectly. – James Daly Dec 27 '12 at 17:16