lundi 8 juin 2015

Javascript pattern for library with dependencies

Sometimes I've come across a particular pattern present in some javascript libraries. Maybe it's a coincidence but I've seen it in libraries with dependencies. The syntax is as follows (The sample is taken from Backbone which has a hard dependency on underscore)

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
            root.Backbone = factory(root, exports, _, $);
        });
  } else if (typeof exports !== 'undefined') {
      var _ = require('underscore');
      factory(root, exports, _);
  } else {
      root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }

}(this, function(root, Backbone, _, $)

Can someone explain why this pattern is used. The parts I don't understand very well is the use of the factory variable, why is testing for the property define.amd and why exports is loaded as a dependency in define(['underscore', 'jquery', 'exports'].

I'm familiar with AMD modules but seeing this makes me wonder if I should use the same pattern if I'm writting a library with a dependency or this pattern should be used everytime even if I have no dependencies at all.

Aucun commentaire:

Enregistrer un commentaire