Backbone.js collectin throw the error

后端 未结 1 585
一个人的身影
一个人的身影 2021-01-26 08:47

I am(as a beginner) making a small backbone function to append my links, for this i using the collection to be assigned model,

But the collection throw the error.. any o

相关标签:
1条回答
  • 2021-01-26 09:16

    Models are used to store and manage individual chunks of data. In your case that would be a single name/href pair. Usually you use Backbone.Model.extend to create a model "class" with all your model-specific methods and properties and then you create instances of that model with new or set that model "class" as a collection's model property so that the collection can create new instances of the model.

    Your model should look more like this:

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

    Notice that there's no new in there as we're just making a "class" to base our model instances on. Then we hook the model up to a collection (again using extend with no new):

    var Collection = Backbone.Collection.extend({
        model: Model
    });
    

    Now you can create an instance of the collection and hand it an array of data for the models:

    var links = new Collection([
        { name: 'Yahoo', href: 'http://www.yahoo.com' },
        { name: 'Gmail', href: 'http://www.gmail.com' },
        { name: 'Bing',  href: 'http://www.bing.com'  }
    ]);
    

    You'll often pass the collection to the view rather than making the view instantiate the collection; Backbone will automatically set this.collection if you say new SomeView({ collection: some_collection }) so you can:

    var View = Backbone.View.extend({
        //...
        initialize: function() {
            this.template = $('#temp').children();
        },
    

    and say new View({ collection: links }) and access the collection through this.collection elsewhere in the view.

    A collection is a collection of several models (sort of like an array) and it will have various useful Underscore methods mixed in so you can iterate through the collection like this:

    render: function() {
        this.collection.each(function(link) {
            var li = this.template.clone().find('a').attr('href', link.get('href')).text(link.get('name'));
            this.$('ul').append(li);
        }, this);
    }
    

    Also notice the use of get to access model attributes, model attributes and object properties are different things. You can also use toJSON to flatten all the data at once. The final this argument to each makes this inside the callback the view. Backbone already supplies a this.$el.find() alias in the view's this.$() method so I switch to that as well.

    Here's a simplified demo: http://jsfiddle.net/ambiguous/WSqLM/

    0 讨论(0)
提交回复
热议问题