Reactive Dependency Injection


#1

Hi there,

I am trying to figure out the best way to use Flux architecture in Meteor and I run into some problems with globals, dependencies, and loading order. I know it’s a common issue in Meteor.

I have fallen in love with Meteor’s reactivity lately, so I thought: why not use it for dependencies?

The code turned out to be really simple:

var _objs = {};
var _list = new ReactiveDict();

Dependency = {
  add: function(name, object){
    _objs[name] = object;
    _list.set(name, true);
    Tracker.flush();
  },
  get: function(name){
    _list.get(name);
    return _objs[name];
  },
  autorun: function(func){
    Tracker.autorun(func);
  }
}

And the API is very simple as well.

Declare your dependencies inside your object/class like this:

var _otherObject, _anotherObject;
Dependency.autorun(function(){
  _otherObject   = Dependency.get('OtherObject');
  _anotherObject = Dependency.get('AnotherObject');
});

And after object/class creation, add it to the system like this:

var otherObject = new OtherObject();
Dependency.add('OtherObject', otherObject);

I have done an example and it’s working great so far:


I haven’t deployed it to meteor.com because it’s pretty useless.
Take a look at the code instead.

I have created a package as well, you can add it using:

meteor add meteorflux:reactive-dependency

You can use it even if you don’t use Flux or MeteorFlux, of course.
Actually, MeteorFlux is not even documented yet (sorry!).

It solves some Meteor issues:

  • No more globals.
  • No more loading order chaos.
  • You can use circular dependencies.
  • You can use the dependency injection pattern.

Here is the Github repo with more info:

And that’s it… what do you think? :blush:

BTW, I’d love to know about the possible performance impact of this technique. Is it ok? Is it bad?


#2

May I ask: how does your work compare with this . . .

space:base