一个视图连接到多个模型 [英] One View connected to multiple models
问题描述
我有以下问题...
MyView的
连接到两个视图: TaskModel
和的usermodel
MyView
which is connected to two views: TaskModel
and UserModel
TaskModel = {id: 1, taskName: "myTask", creatorName: "myName", creator_id: 2 },
UserModel = {id: 2, avatar: "someAvatar"}
该视图应该显示
{{taskName}}, {{creatorName}}, {{someAvatar}}
正如你可以看到获取的 TaskModel
和的usermodel
应该是同步的,因为 userModel.fetch
taskModel.get的需求(creator_id)
As you can see the fetch of TaskModel
and UserModel
should be synchronized, because the userModel.fetch
needs of taskModel.get("creator_id")
哪种方法,你推荐我来显示/处理视图和两个型号?
Which approach do you recommend me to display/handle the view and the two models?
推荐答案
您可以使视图足够聪明,不会渲染,直到它有它需要的一切。
You could make the view smart enough to not render until it has everything it needs.
假设你有一个用户和一项任务,他们两个传递给视图的构造函数:
Suppose you have a user and a task and you pass them both to the view's constructor:
initialize: function(user, task) {
_.bindAll(this, 'render');
this.user = user;
this.task = task;
this.user.on('change', this.render);
this.task.on('change', this.render);
}
现在您具有在用户和任务都引用和被监听两个改变
事件视图。然后,渲染
方法可以询问型号,如果他们有他们应该拥有的一切,例如:
Now you have a view that has references to both the user and the task and is listening for "change"
events on both. Then, the render
method can ask the models if they have everything they're supposed to have, for example:
render: function() {
if(this.user.has('name')
&& this.task.has('name')) {
this.$el.append(this.template({
task: this.task.toJSON(),
user: this.user.toJSON()
}));
}
return this;
}
所以渲染
将等到两个 this.user
和 this.task
它在适当的HTML填充之前完全加载;如果已加载的车型之前被调用,那么它呈现什么,并返回一个空的占位符。这种方法使所有很好地隐藏掉视图内视图的逻辑,它属于哪里,很容易推广。
So render
will wait until both the this.user
and this.task
are fully loaded before it fills in the proper HTML; if it is called before its models have been loaded, then it renders nothing and returns an empty placeholder. This approach keeps all of the view's logic nicely hidden away inside the view where it belongs and it easily generalizes.
演示: http://jsfiddle.net/ambiguous/rreu5jd8/
您也可以使用下划线的 的isEmpty
(其中混合成骨干机型,而不是检查特定属性):
You could also use Underscore's isEmpty
(which is mixed into Backbone models) instead of checking a specific property:
render: function() {
if(!this.user.isEmpty()
&& !this.task.isEmpty()) {
this.$el.append(this.template({
task: this.task.toJSON(),
user: this.user.toJSON()
}));
}
return this;
}
这是假设你没有当然的缺省值。
That assumes that you don't have any defaults of course.
演示: http://jsfiddle.net/ambiguous/4q07budc/
这篇关于一个视图连接到多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!