Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm rewriting a simple app using HTML/CSS/JavaScript that creates animations with images using intervals, and there's a bunch of buttons that controls these animations.

It's scaling and becoming really messed up, with logic mixed with DOM manipulations via jQuery all through one JavaScript script file.

I've decided to use the Module design pattern. Based on my description of the app, is there a problem with this callback implementation for a module, or with the module implementation?

In this example, what is the best approach to declare private variables and give access to them through the public API? Getters and setters? Are they really necessary? I want to write readable code but I don't want to over-architect things.

(function($) {

  $.Module = function(options){
    var module = {
      options: $.extend({
        callbacks: {
          start: false
        }
      }, options),
      start: function(callback){
        //console.log('private start method');
        if(typeof callback === "function") {
            callback();
        }
      }
    }

    // public api
    return {
      start: function(){
        //console.log('public start method');
        module.start(module.options.callbacks.start);
      }
    }
  }

}($));

var myModule = $.Module({
  callbacks: {
    start: function(){
      console.log('start callback!');
    }
  }
})

myModule.start();

Here is a sample.

this next issue is actually just for the sake of learning

That seems to work to me so far. But I've seen other implementations that have some code that look like this:

callback: function(method) {
    if(typeof method === "function") {
        var args = [];

        for(var x = 1; x <= arguments.length; x++) {
            if(arguments[x]) {
                args.push(arguments[x]);
            }
        }

        method.apply(this, args);
    }
},

I'm not sure what this last code is supposed to do. Is it intended to return data to the callback function I registered when instantiating the module?

share|improve this question

1 Answer 1

The last piece is: Whoever is calling that callback: function itself may be passing params to it, which need to be repackaged into a genuine array from their source in the (implementation deficient) arguments array, before they can be passed to method via apply which is essentially tacking on the method method to this and calling it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.