2
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 24, 2014 at 21:35
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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.

answered Jul 29, 2014 at 14:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.