Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Created November 21, 2013 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasBurleson/7574511 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/7574511 to your computer and use it in GitHub Desktop.
Refactor Dash.js JavaScript class - to use AMD pattern, eliminate requirement to construct with `new`, remove unnecessary use of Promises.
MediaPlayer.rules.BaseRulesCollection = function () {
"use strict";
var rules = [];
return {
downloadRatioRule: undefined,
insufficientBufferRule: undefined,
//limitSwitchesRule: undefined,
getRules: function () {
return Q.when(rules);
},
setup: function () {
var self = this;
self.getRules().then(
function (r) {
r.push(self.downloadRatioRule);
r.push(self.insufficientBufferRule);
//r.push(self.limitSwitchesRule);
}
);
}
};
};
MediaPlayer.rules.BaseRulesCollection.prototype = {
constructor: MediaPlayer.rules.BaseRulesCollection
};
@ThomasBurleson
Copy link
Author

While reviewing the very interesting Git project Dash.js, I noticed some repeating usages that seem unnecessary, dangerous, or verbose.

Below is a refactored version of the above class:

(function( Q )
{
  "use strict";
  var dependencies = [ ];

  define( dependencies, function() 
  {
    var BaseRulesCollection = function () 
        {
          var self = {
                downloadRatioRule       : undefined,
                insufficientBufferRule  : undefined,
                limitSwitchesRule       : undefined,

                rules : function () 
                        {
                          var nonNulls = function( el ) 
                              { 
                                return el != null; 
                              },
                              list = [ 
                                self.downloadRatioRule,
                                self.insufficientBufferRule,
                                self.limitSwitchesRule
                              ];

                          return list.filter( nonNulls );
                        }
              };

          // publish isolated instance 
          return self;
        };

      // Publish constructor array; @see 
      // http://solutionoptimist.com/2013/09/30/requirejs-angularjs-dependency-injection/

      return [ BaseRulesCollection ];
    });


}( Q ));

Items of note:

  1. Use of Module Pattern to protect and scope variables
  2. Use of Require.js to define dependencies (can use Browserify) to port to non-RequireJS apps
  3. Remove use of Q since the original implementation's use of Promises was superfulous
  4. Dynamic construction of the rules array
  5. Removed use of this scope and the requirement to use new BaseRulesCollection()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment