2
votes

I'm pretty new to Backbone and Marionette and am having a tough time getting my views to communicate.

I've got a composite view that displays a list of items. To add a new item to the list, I have a popup modal that opens in a new item view that is separate from the composite view.

I'm not sure that this is the best way to do this, but in the modal, I created a new instance of the collection with all of the items and added the new item to that collection. This new item shows up in the original composite view, but only after I refresh the page.

I can't seem to figure out how to get the composite view to listen for the add event and render the new model after it is added.

Am I on the right track here? If not, what should I be doing to add to a collection from a modal?

2

2 Answers

1
votes

I think I got this figured out. Instead of creating a new collection in the modal view, I passed in the collection from the composite view as a parameter when I created the modal view. Now, when I add a new model in the modal, the 'add' event is automatically triggered on both versions of the collection and the view automatically renders the new model. No need to bind any extra events like I was thinking.

0
votes

Your solution will work, but means your views are pretty tightly coupled. You might want to look into using events instead (see How do I send a model that was clicked on within a ItemView to another ItemView that is on the same page?)

How your functionality would work with events:

  1. Within the modal, you enter the data for the model to create
  2. When you press the "save" button,
    1. you validate and save the model var myNewModel = ...
    2. you trigger an event: MyApp.MySubApp.trigger("item:add", myNewModel)
  3. In the controllerfor the list view, you listen to that event, and add the new model to the collection.

The handler code in your controller would look something like:

MyApp.MySubApp.on("item:add", function(model){
  this.myCollection.add(model);
});

If you'd like to learn more about using events, check out 2 Marionette tutorials I wrote:

Both use events to communicate information within the apps.

In addition, basic events are also explained here: http://samples.leanpub.com/marionette-gentle-introduction-sample.pdf