Search code examples
javascripteventsbackbone.jstriggersmarionette

Marionette difference between command/comply, listento/trigger, request/reply


I'm working on some legacy code and have come across 3 similar constructs for triggering events

  1. command/comply
    • trigger: .command('update:mySetting', newSetting);
    • handle: .comply('update:mySetting', myCallback);
  2. listento/trigger
    • trigger: .trigger('change');
    • handle: .listenTo(myModel, 'change', myCallback);
  3. request/reply
    • trigger: .request('change');
    • handle: .reply('change', myCallback);

What is the difference between these events and when should I use each of them?

Thanks

Note: I'm not sure if all of them come from marionette


Solution

  • https://github.com/marionettejs/backbone.radio

    reply is used when you need to return a value when a request is made.

    For example

    Radio.channel('global').reply('something', function() { return 'something';});
    
    // can also be
    //     Radio.channel('global').reply('something', 'something');
    
    
    //... somewhere else in the code base
    
    // someValue = 'something'
    var someValue = Radio.channel('global').request('something');
    

    You don't have to return anything with request/reply and just use it as a way to run a function. Doing this will make it work like command/comply, which makes command/comply not needed.

    You can have one reply for a request, so redefining a reply will overwrite the last definition. It's one to one, for a reply you have a corresponding request.

    // before
    Radio.channel('global').reply('something', function() { return 'something';});
    
    // somewhere else, it gets changed
    Radio.channel('global').reply('something', 'not something');
    

    Make changes at your discretion.

    trigger/listenTo is the typical event system.

    trigger can emit an event from anywhere in the code.

    listenTo allows many listeners to listen to that event to do what is needed when fired.

    Radio.channel('global').trigger('myEvent');
    
    // somewhere in the code
    
    view1.listenTo(Radio.channel('global'), 'myEvent', function() {
      // do something
    });
    
    // somewhere else in the code
    
    view2.listenTo(Radio.channel('global'), 'myEvent', function() {
      // also do something
    });