Search code examples
reactjsreactjs-flux

Extended event emitter functions across stores are clashing in Flux


I have multiple Flux stores. Now clearly, all of them are extending the same Event emitter singleton. This has led to events across stores clashing with each other (even the most common, emitChange). There seems to be no difference between doing Store1.getID() and Store2.getID(), because stores seem to be one large object extended from every other store. What am I doing wrong?

I have been having this issue for a while now, and its driving me nuts. I am sure this has a simple answer that I am missing. It's one of the reasons I am waiting for relay and GraphQL.

EDIT: What all my stores look like in code.

var Events = require('events'), extend = require('deep_extend'),
    EventEmitter = Events.EventEmitter,
    CHANGE_EVENT = 'change';

var SomeStore = extend(EventEmitter.prototype, {
    someGetter: function(){
        return _someVar;
    },
    dispatchToken: AppDispatcher.register(function(action) {
        switch(action.type) {
            case 'SOME_ACTION':
                _someVar = 'someValue'
                break;

            default:
                return true;
        }

        SomeStore.emitChange();
        return true;
    })
});

return SomeStore;

Solution

  • stores seem to be one large object extended from every other store.

    There must be some problem with how you extend from EventEmitter otherwise your code should be working fine.

    Now that there are a few ways to do the same thing, here is how facebook implemented it in their official examples:

    var assign = require('object-assign');
    var EventEmitter = require('events').EventEmitter;
    var TodoStore = assign({}, EventEmitter.prototype, {
        ...
    

    UPDATE

    Now looking at your code

    extend(EventEmitter.prototype, {
    

    is actually writing on the prototype itself, hence the errors you got. Instead you should be extending an empty object:

    extend({}, EventEmitter.prototype, {