Reputation: 19896
Problem:
I have 3 UI components on a screen:
Top menu's Option
. Its inner content varies depending on which Left menu's item
being selected. For example, A selected will show 2 input boxes while B would show 3 input boxes, etc...The way it works is that user will select left menu item, then they click Top menu's Option and the Form content will show up.
Top menu has TopMenu
model
{
isSelected: false
}
Left menu has LeftMenuCollection
which contains such model
{
id: 0
label: "No label yet"
}
Form content has FormContentModel
which is too long to put in here.
I have the 2 views: TopMenuView
and LeftMenuView
for TopMenu
and LeftMenuCollection
. But the view for Form content view (let call FormContentView
) has to get values from both TopMenu
and LeftMenuCollection
in order to know when to be visible and what to show after being visible.
Current Idea:
User's action on LeftMenuView
will trigger event and FormContentView
will populate HTML in the hidden DOM according to what being selected.
TopMenuView
will trigger FormContentView
to be visible.
Then FormContentView
will be save into its own FormContentCollection
.
For #1 and #2, I just has use the PubSub model like here: fire an event from one view to another in backbone
But since I use Backbone Boilerplate https://github.com/tbranyen/backbone-boilerplate. I am planning to do this because the app object is already created in app.js:
app.PubSub = _.extend({}, Backbone.Events)
Question:
How and where do I create that PubSub object? Is it in the router.js?
Is PubSub the right way to do this? I was thinking about of "composite model" too by combining TopMenu
and LeftMenuCollection
under another FormContentCollection
but most people on internet said using PubSub.
Upvotes: 1
Views: 1654
Reputation: 2051
Create the pubsub as soon as you define your "app" variable.
I prefer to attach the PubSub directly to the Backbone object and I do it right after backbone loads. (I written about it before: Backbone.js global notifications)
Here's another idea that might be simpler:
Create a new model and share it between all views.
(Note that you can add a second model to views, they don't have to be set to view.model)
The Left and Top views can .set() its attributes and the Form view can bind to changes using .on('change', function...) and respond by showing/hiding the view.
Upvotes: 2