动态改变骨干模型

时间:2015-01-15 12:19:17

标签: backbone.js

我有一个列表模型,例如ProductBookPhone其中一些可能会从另一个继承。

我尝试构建一个from来添加不同的产品,表单视图应该根据用户选择的类型进行更改。

这是现在尝试过的:

    var Product = Backbone.Model.extend({
        defaults: {
            name: null,
            price: 0,

            type: null, /** phone or book or something else*/

            phoneColor: null,
            phoneWeight: 0,

            bookCategory: null,
            bookAuthor: null
        }
    });
    var ProductFormView = Backbone.View.extend({
        ..........
        render: function () {
            var type = this.model.get('type');
            switch (type) {
                case 'phone':............
                    break;
                case 'book':.........
                    break;
            }
            return this;
        }
    });

将所有属性放到Product,然后根据不同的模型类型呈现表单,现场演示:http://jsfiddle.net/57ra37vg/

即使它现在有效,但我认为这是一个坏主意,在我看来,基类Product不应包含太多属性。我喜欢这样的事情:

    var Product = Backbone.Model.extend({
        defaults: {
            name: null,
            price: 0,

            type: null, /** phone or book or something else*/
        }
    });

    var Book = Product.extend({
        defaults:{
            bookAuthor:null,
            bookCategory:null
        }
    });

    var ProductView = Backbone.View.extend({
        render:function(){}
    });

    var BookView = ProductView.extend({
        render:function(){}
    });
    var PhoneView = ProductView.extend({
        render:function(){}
    });

每个子产品都拥有其属性和视图。通过这种设计,当用户通过选择选项更改产品类型时,如果我可以将当​​前模型更改为其他类型的模型,则刷新视图。

但似乎我无法动态地将Book的实例更改为Phone

那么你如何进行设计?

1 个答案:

答案 0 :(得分:0)

拥有单独的视图和模型是很好的。在这个问题中,我们可以使用FormView,它可以包含产品视图。每个产品视图都可以拥有自己的模型,而不是动态更改模型。我会选择这种设计。

var Product = Backbone.Model.extend({
    defaults: {
        name: null,
        price: 0
    }
});

var Book = Product.extend({
    defaults:{
        bookAuthor:null,
        bookCategory:null
    }
});

var Phone = Product.extend({
    defaults:{
        color:null,
        weight:null
    }
});    

var ProductView = Backbone.View.extend({
    render:function(){}
});

var BookView = ProductView.extend({
    initialize: function(options) {
        this.model = new Book(options);
    },

    render:function(){}
});
var PhoneView = ProductView.extend({
    initialize: function(options) {
        this.model = new Phone(options);
    },
    render:function(){}
});

var FormView = Backbone.View.extend({
      tagName: 'form',
      defaults: {
        productView: null
      },
      events: {
          'change select': 'type_change'
      },
      type_change: function () {
          var productType = this.$el.find('select').val()
          this.productView.remove();
          this.productView = this.getProductView(productType);
          this.productView.render();
      },
      getProductView(product) {
          if(product == "book")
              return new ProductView();
          return new BookView();
      }
});
相关问题