There's a couple of approaches I've used. One is to have both views hold references to the same model - then you can simply listen for events from the model in question from whichever view needs to know about it. The second is to use an event aggregator, essentially an event object that provides a place to route events through so you can reduce the number of objects you need to have your views listening to events from. Which I use is generally guided by the complexity of the application and how many model/collection objects from which I need to route events.
How do I pass events between Backbone.js views?
-
27-09-2022 - |
Pregunta
I'm excercizing with my first Backbone app, CRUD style.
I have modelListView
, with an Edit button linking to the modelView
. The modelView has a delete button to destroy the model.
Now what I want to achieve is to show user a success message when he returns to the modelListView
and when the model has been successfully deleted.
I have triggered a model:deleted
event within success
but the modelListView
's listener:
initialize: function(){
this.on('wine:deleted', function(){
alert('wine:deleted')
})
},
can't "hear" that. What is the best practice for that sort of inter-view communication?
Solución
Otros consejos
I think your basic problem is this line:
this.on('wine:deleted', function(){
you said that line of code came from modelListView
, but the thing is, Views
don't have an on
method (only Model
s and Collection
s do). I think what you're looking for is:
this.model.on('wine:deleted', function(){
but even that's not quite right because the namespacing seems funny. If I assume you're doing:
this.trigger('deleted');
in your Wine model, then to catch that event you'd just need:
this.model.on('deleted', function(){
However, even that seems like a bit of overkill, because Backbone already has an event that you can use when a Model
gets destroyed, that doesn't require any extra trigger
statements:
this.model.on('destroy' function(){
Hope that helps.