Search code examples
javascriptreactjsfluxrefluxjs

Reflux actions global debugging


Is there a way how to globally console.log() all the fired actions in Reflux? Ideally prints theirs parameters at the same time.


Solution

  • Like Cory Danielson said, Reflux uses EventEmitter. And you can insert your own EventEmitter-implementation like this:

    Reflux.setEventEmitter(require('events').EventEmitter);
    

    So you want to inject an EventEmitter constructor there that has debugging enabled, something like this:

    var EventEmitter = require('events').EventEmitter;
    
    function DebugEventEmitter() {
      var realEmitter = new EventEmitter();
    
      var origEmit = realEmitter.emit;
      realEmitter.emit = function () {
        console.log('emitting', arguments);
        return origEmit.apply(realEmitter, arguments);
      };
    
      return realEmitter;
    }
    
    Reflux.setEventEmitter(DebugEventEmitter);
    

    This only hijacks the emit method which is used to emit events, but you can of course hijack any other method on EventEmitter and add logging.

    EDIT

    Since Reflux doesn't pass the action name to the emitted event, here's another solution which is way more hackish, but it should work for debugging purposes.

    var Reflux = require('reflux');
    
    // Do this before any code is calling Reflux
    var origCreateAction = Reflux.createAction;
    Reflux.createAction = function () {
      var action = origCreateAction.apply(Reflux, arguments);
    
      var wrapper = function () {
        console.log(action.actionName, 'called with args: ', arguments);
        return action.apply(action, arguments);
      };
    
      for (var key in action) {
        wrapper[key] = action[key];
      }
    
      return wrapper;
    };
    
    // Example using actions and triggering them, which logs
    // with our wrapper
    var Actions = Reflux.createActions([
      'statusUpdate',
      'statusEdited',
      'statusAdded'
    ]);
    
    Actions.statusUpdate.listen(function () {
      console.log('status update called');
    });
    
    Actions.statusUpdate({test: 1});