2012-02-07 17 views

Respuesta

13

Aquí hay un buen artículo sobre el uso de un event aggregator.

¿Alguien puede explicar cómo implementar el despachador para comunicarse de una vista a otra? ¿Dónde debo colocar el código en mi aplicación?

Probablemente tengas algún tipo de objeto App Controller, que controlará el flujo de la aplicación, creando vistas, modelos, etc. Este también es un buen lugar para el agregador de eventos.

Desde mi punto de vista, creo que el artículo lo explica bastante bien.

0

Recientemente necesité un EventDispatcher para manejar una gran cantidad de eventos sin perder la pista de sus nombres y su comportamiento.

Quizás te ayude también.

Aquí un ejemplo simple vista:

define(['backbone', 'underscore', 'eventDispatcher'], 
    function(Backbone, _, dispatcher){ 

     new (Backbone.View.extend(_.extend({ 
      el: $('#anyViewOrWhatever'), 
      initialize: function() { 
       window.addEventListener('resize', function() { 
        // trigger event 
        dispatcher.global.windowResize.trigger(); 
       }); 

       // create listener 
       dispatcher.server.connect(this, this.doSomething); 

       // listen only once 
       dispatcher.server.connect.once(this, this.doSomething); 

       // remove listener: 
       dispatcher.server.connect.off(this, this.doSomething); 
       // remove all listener dispatcher.server.connect from this: 
       dispatcher.server.connect.off(null, this); 
       // remove all listener dispatcher.server.connect with this method: 
       dispatcher.server.connect.off(this.doSomething); 
       // remove all listener dispatcher.server.connect no matter what and where: 
       dispatcher.server.connect.off(); 

       // do the same with a whole category 
       dispatcher.server.off(/* ... */); 

       // listen to all server events 
       dispatcher.server.all(this, this.eventWatcher); 

      }, 
      doSomething: function(){ 

      }, 
      eventWatcher: function(eventName){ 

      } 

     }) 
    ))(); 
}); 

Aquí el EventDispatcher con algunos eventos de ejemplo. Los eventos en sí están predefinidos en la plantilla Object. Su IDE debería reconocerlos y guiarlo a través de la lista.

Como puede ver, el despachador se ejecuta solo. Solo su vista o lo que sea que necesite los métodos de eventos subyacentes de Backbone.

// module eventDispatcher 
define(['backbone', 'underscore'], function (Backbone, _) { 

    var instance; 
    function getInstance() { 
     if (!instance) { 
      instance = createInstance(); 
     } 
     return instance; 
    } 
    return getInstance(); 

    function createInstance() { 
     // dummy function for your ide, will be overwritten 
     function e (eventContext, callback) {} 
     var eventHandler = {}, 

      // feel free to put the template in another module 
      // or even more split them in one for each area 
      template = { 
       server: { 
        connect: e, 
        disconnect: e, 
        login: e, 
        logout: e 
       }, 
       global: { 
        windowResize: e, 
        gameStart: e 
       }, 
       someOtherArea: { 
        hideAll: e 
       } 
      }; 

     // Create Events 
     _.each(template, function (events, category) { 
      var handler = eventHandler[category] = _.extend({}, Backbone.Events); 
      var categoryEvents = { 
       // turn off listener from <category>.<**all events**> with given _this or callback or both: 
       // off() complete purge of category and all its events. 
       // off(callback) turn off all with given callback, no matter what this is 
       // off(null, this) turn off all with given this, no matter what callback is 
       // off(callback, this) turn off all with given callback and this 
       off: function (callback, _this) { 
        if(!callback && _this){ 
         handler.off(); 
        }else{ 
         _.each(template[category], function(v, k){ 
          k != 'off' && template[category][k].off(callback, _this); 
         }); 
        } 
       } 
      }; 
      events.all = e; 
      _.each(events, function (value, event) { 
       // create new Listener <event> in <category> 
       // e.g.: template.global.onSomething(this, fn); 
       categoryEvents[event] = function (_this, callback) { 
        _this.listenTo(handler, event, callback); 
       }; 
       // create new Listener <event> in <category> for only one trigger 
       // e.g.: template.global.onSomething(this, fn); 
       categoryEvents[event].once = function (_this, callback) { 
        _this.listenToOnce(handler, event, callback); 
       }; 
       // trigger listener 
       // e.g.: template.global.onSomething.trigger(); 
       categoryEvents[event].trigger = function (debugData) { 
        console.log('**Event** ' + category + '.' + event, debugData ? debugData : ''); 
        handler.trigger(event); 
       }; 
       // turn off listener from <category>.<event> with given _this or callback or both: 
       // off() complete purge of category.event 
       // off(callback) turn off all with given callback, no matter what this is 
       // off(null, this) turn off all with given this, no matter what callback is 
       // off(callback, this) turn off all with given callback and this 
       // e.g.: template.global.onSomething.off(fn, this); 
       categoryEvents[event].off = function (callback, _this) { 
        handler.off(event, callback, _this); 
       } 

      }); 
      template[category] = categoryEvents; 
     }); 

     return template; 
    } 

}); 

El comportamiento del sistema Backbones Event no se ve afectado de ninguna manera y se puede utilizar de forma normal.

Cuestiones relacionadas