backbone-eventbroker icon indicating copy to clipboard operation
backbone-eventbroker copied to clipboard

Change request to readme

Open jpgrace opened this issue 11 years ago • 1 comments

In the readme you show an example of EventBroker like this:

var Users = Backbone.Collection.extend{{
    initialize: function(){
      // subscribe to an event ...
      Backbone.EventBroker.on('users:add', this.add, this);
    },
    add: function(user) {
      console.log(user.id);
    }
};

var UserEditor = Backbone.View.extend({
     el: '#editor',
     initialize: function(broker){
        this.$userId = this.$('#userId');
     },
     add: function() {
       // publish an event ...
       var user = new User({id: this.$userId().val()});
       Backbone.EventBroker.trigger('users:add', user);
    }
};

I believe that it would probably be better for your users to design their code like this:

var Users = Backbone.Collection.extend{{
    initialize: function(){
      // subscribe to an event ...
      Backbone.EventBroker.register('UserEditor:addRequest', this.add, this);
    },
    add: function(user) {
      console.log(user.id);
    }
};

var UserEditor = Backbone.View.extend({
     el: '#editor',
     initialize: function(broker){
        this.$userId = this.$('#userId');
     },
     add: function() {
       // publish an event ...
       var user = new User({id: this.$userId().val()});
       Backbone.EventBroker.trigger('UserEditor:addRequest', user);
    }
};

The advantage being that the triggering view object doesn't need to (and shouldn't need to IMHO) what methods it's triggering. It only needs to know how to trigger an event. The objects that care about that event can then listen for it and act accordingly. In the future new view objects in this app could also 'register' the 'UserEditor:addRequest' to fire one of its methods at that time. This design would prevent users from adding multiple trigger statements in one method, which I believe is less maintainable because it is less encapsulated.

I'd love to hear your thoughts.

jpgrace avatar May 02 '13 13:05 jpgrace