Backbone Collection with multiple models?

前端 未结 4 1961
长发绾君心
长发绾君心 2020-12-13 21:52

I\'m learning Backbone.

I want to create a list that can contain different models, with different attributes.

For example, listing folder contents, which co

4条回答
  •  旧时难觅i
    2020-12-13 22:12

    You could also do it the backbone way. Check out the docs backbone collection

    Basically you would create different models adding a tie breaker attribute say "type" in this case.

    var file = Backbone.Model.extend({
            defaults: {
                // will need to include a tie breaker attribute in both models
                type: 'file'
            }
        }),
        folder = Backbone.Model.extend({
            defaults: {
                // tie breaker
                type: 'folder'
            }
        });
    
    var fs = Backbone.Collection.extend({
        model: function(model, options) {
            switch(model.type) {
                case 'file':
                    return new file(model, options);
                case 'folder':
                    return new folder(model, options);
            }
        }
    });
    
    // after that just add models to the collection as always
    new fs([
        {type: 'file',name: 'file.txt'},
        {type: 'folder',name: 'Documents'}
    ]);
    

提交回复
热议问题