javascript Backbone.js:组合多个模型的复杂视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7385629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:56:28  来源:igfitidea点击:

Backbone.js: complex views combining multiple models

javascriptmodel-view-controllerbackbone.js

提问by Sander

So far all tests and tutorials i've been trying, to get the structure in my head, show me that a view is bound to 1 model.

到目前为止,我一直在尝试的所有测试和教程都是为了在我的脑海中获得结构,向我展示一个视图绑定到 1 个模型。

lets say i have a small app to store and manage contact details (an address book) i have multiple users that can login and they each have their own collection of contacts.

假设我有一个小应用程序来存储和管理联系人详细信息(地址簿)我有多个用户可以登录,他们每个人都有自己的联系人集合。

the user detail view would be bound to the user model same goes for contacts

用户详细信息视图将绑定到用户模型与联系人相同

but say i would like to show a grid combining those two X axis showing all contacts in the app Y axis showing all users,

但是说我想显示一个结合这两个 X 轴的网格,显示应用程序 Y 轴中显示所有用户的所有联系人,

how does this work? do i need to create a new model for this, to bind to a new view?

这是如何运作的?我需要为此创建一个新模型以绑定到新视图吗?

you get the idea, its just a theoretical example i am not building that app but its to get the idea of having a view combining multiple models

你明白了,这只是一个理论上的例子,我不是在构建那个应用程序,而是为了获得组合多个模型的视图的想法

回答by Brian Genisio

In that case, I'd consider a dynamic model with both of your sub-models. In your route handler, you could do something like this:

在这种情况下,我会考虑使用两个子模型的动态模型。在您的路由处理程序中,您可以执行以下操作:

var model = new Backbone.Model();
model.set({contacts: new ContactsModel(), users: new UsersModel()});
var view = new GridView({model: model});

Of course, there is nothing stopping you from passing in the models separately:

当然,没有什么可以阻止您单独传递模型:

var contacts = new ContactsModel();
var users = new UsersModel();
var view = new GridView({model: contacts, users: users})

I still prefer the composite approach of the first because it doesn't conflate what the model is.

我仍然更喜欢第一种的复合方法,因为它不会混淆模型是什么。

回答by ximonn

You can also consider merging both models, if you are sure they dont use the same parameters.

如果您确定它们不使用相同的参数,您也可以考虑合并两个模型。

var modelA = new myModel({ color: "blue" });
var modelB = new otherModel({ age: 35 });

var superModel = new Backbone.Model();
superModel.set(modelA);
superModel.set(modelB);

console.log("color:", superModel.get("color"));
console.log("age:", superModel.get("age"));

take a look at Backbone.Model.extend()as well

看一看Backbone.Model.extend()以及