I have the following problem…
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"}
The view should display
{{taskName}}, {{creatorName}}, {{someAvatar}}
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:
Now you have a view that has references to both the user and the task and is listening for
"change"events on both. Then, therendermethod can ask the models if they have everything they’re supposed to have, for example:So
renderwill wait until both thethis.userandthis.taskare 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.Demo: http://jsfiddle.net/ambiguous/rreu5jd8/
You could also use Underscore’s
isEmpty(which is mixed into Backbone models) instead of checking a specific property:That assumes that you don’t have any defaults of course.
Demo: http://jsfiddle.net/ambiguous/4q07budc/