What is a good method to send a message from a Child view to its parent collection view in Backbone.js or Marionette.js?

What is a good way to send a message from a Child view to its parent collection view in Backbone.js or Marionettejs?

I usually send a message through a collection:

ChildView = Backbone.Marionette.ItemView.extend({ send_message: function(){ this.model.collection.trigger('some-message'); } }) ParentCollectionView = Backbone.Marionette.CollectionView.extend({ // ON RENDER onRender: function(){ this.listenTo(this.collection, 'some-message', this.do_something); } // DO SOMETHING do_something: function(){ alert('did something'); } }); 

I think this is wrong because:

  • I send a message from the child view through the data back to the parent view
  • In this case, the message does not apply to data, its strict message passing between the representations of the presentation of the material
  • A model may belong to more than one collection.

Instead, I would like to send the message directly from the child view to its parent collection view. (in fact, I use a composite view, not sure if this matters, I would like the example to be simple).

+5
source share
2 answers

Either the parent view emits the event directly, and the parent listens for it:

 ChildView = Backbone.Marionette.ItemView.extend({ send_message: function(){ this.trigger('some-message'); } }) ParentCollectionView = Backbone.Marionette.CollectionView.extend({ // ON RENDER onRender: function(){ // no idea how Marionette references its children views // let say this.subview is a reference to your child view this.listenTo(this.subview, 'some-message', this.do_something); } // DO SOMETHING do_something: function(){ alert('did something'); } }); 

Or use a special event emitter that you enter in the subtitle (s)

 ChildView = Backbone.Marionette.ItemView.extend({ send_message: function(){ this.channel.trigger('some-message'); } }) ParentCollectionView = Backbone.Marionette.CollectionView.extend({ initialize: function(){ this.channel = _.extend({}, Backbone.Events); this.listenTo(this.channel, 'some-message', this.do_something); }, // ON RENDER onRender: function(){ // pass the channel to the child // that probably should be done when the child is created this.subview.channel = this.channel; }, // DO SOMETHING do_something: function(){ alert('did something'); } }); 
+4
source

Marionette has a handy feature called triggerMethod that can send events from a child to a parent.

 this.triggerMethod("someMethod", data1...) 

This event was caught by the parent using the onChildview listener.

 onChildviewSomeMethod(childView, data1param, ...) {} 
+1
source

Source: https://habr.com/ru/post/1241329/


All Articles