Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@ThomasBurleson ThomasBurleson commented Nov 21, 2013

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
You can’t perform that action at this time.