【发布时间】:2015-01-15 12:19:16
【问题描述】:
我有一个列表模型,例如Product、Book、Phone,其中一些可能继承自另一个。
我尝试构建一个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。
那么你是如何进行设计的呢?
【问题讨论】:
标签: backbone.js