trying to loop through collection in backbone to o

2019-09-08 03:31发布

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

1条回答
女痞
2楼-- · 2019-09-08 04:13

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
    }
});
查看更多
登录 后发表回答