如何避免过多的模型类
我的应用程序中模型的数量增长很快。我想知道你们关于backbone.js 的标准做法。假设您想要创建一个需要另外 2 个模型的视图。您是否创建一个新的模型类来包含这样的两个模型:
var m = new TheModel({
model1: new Model1,
model2: new Model2
});
var view = new TheView({model:m});
或者您只是执行类似的操作:
var m = {
model1: new Model1,
model2: new Model2
};
var view = new TheView({model:m});
第二个似乎更好,因为那样我就不需要额外的模型类TheModel
。但是,如果我混合使用这两种方法,那么在我看来,我必须记住我正在使用哪种样式,因为如果我想访问 model1
或 model2
那么有两种不同的方式:
var m1 = this.model.get('model1');
或者第二种方案中的这种方式:
var m1 = this.model.model1;
您认为哪种方式更好?您如何组织所有模型和视图?
谢谢!
The number of models has grown quickly in my application. I'm wondering about your standard practices regarding backbone.js. Lets say you want to create a view that requires 2 other models. Do you create a new model class to contain the 2 models like this:
var m = new TheModel({
model1: new Model1,
model2: new Model2
});
var view = new TheView({model:m});
or do you just do something like:
var m = {
model1: new Model1,
model2: new Model2
};
var view = new TheView({model:m});
The second seems better because then I don't need the extra model class TheModel
. But if I mix the two methods, then in my view I have to remember which style I'm using because if I want to get access to model1
or model2
then there are two different ways:
var m1 = this.model.get('model1');
or this way in the second scheme:
var m1 = this.model.model1;
Which is better in your opinion?? How do you organize all the models and views?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非有理由链接您的模型,否则我不会创建聚合其他模型的新模型。第二个选项更好,因为您没有链接它们。
我更喜欢将它们进一步分开:
然后,在视图内,您引用
this.purchases
和this.userthis.model
> 具体来说。您会看到,视图上的
model
属性实际上只是一个约定。视图中的model
属性没有什么特别之处,只是model
属性将在构造函数中自动复制。除此之外,Backbone.View
中没有对model
的引用。当然,这意味着您需要用它做一些事情:
这样,您就可以明确您需要的多个模型。与版本 #2 相比,我更喜欢这个,因为您对视图的要求没有那么明确。
Unless there is a reason to link your models, I would not create a new model that aggregates other models. The second option is better because you are not linking them.
I prefer to separate them even further:
Then, inside the view, instead of referencing
this.model
, you referencethis.purchases
andthis.user
specifically.You see, the
model
property on the views is really just a convention. There is nothing special about themodel
property in the view except that themodel
property will get copied automatically in the constructor. Other than that, there is no reference to themodel
inBackbone.View
.Of course, this means that you need to do something with it:
This way, you are being explicit about the multiple models that you require. I like this better than verison #2 because you are not as explicit about the requirements of the View.
在这种情况下您应该使用集合。在这里您可以阅读有关集合的更多信息:http://backbonetutorials.com/what-is-a-集合/
You should use Collections in this case. Here you can read more about Collections: http://backbonetutorials.com/what-is-a-collection/