2

I have a namespace setup like this:

var myApp = {};
(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;
    }
})(myApp);
window.console && console.log(
    myApp.next(),
    myApp.next(),
    myApp.reset(),
    myApp.next()
) //0, 1, undefined, 0

I now want to to have a callback from myApp which i can catch outside of the namespace..

Any ideas how to set that up with my namespace setup?

For example something like this:

myApp.setCallback('next', function() {
    alert('hello');
 });
Alosyius
  • 8,771
  • 26
  • 76
  • 120
  • 3
    What do you mean by *"a callback from myApp which i can catch outside"*? – Joseph May 11 '13 at 12:13
  • answered [something similar](http://stackoverflow.com/questions/16427077/add-function-to-object/) couple days ago ... – Tim Vermaelen May 11 '13 at 12:14
  • I guess you would have to pass a callback to all the inner functions and check on that callback when the function executes, and then run it..(so you can either pass a callback or not) – vsync May 11 '13 at 12:21
  • Perhaps you could use something like an "event"-pattern, so your app triggers the event "next", and every other object subscribed to this event could do something. – Thomas Junk May 11 '13 at 12:23

2 Answers2

3

You can test for the existance of a callback and run the function if it exists:

var myApp = {};

(function(context) {
    var id = 0;

    context.next = function() {
        return id++;
    };

    context.reset = function() {
        id = 0;

        if(typeof this.onreset === 'function') {
            this.onreset();
        }
    }
})(myApp);


myApp.onreset = function() {};
Tom Elmore
  • 1,980
  • 15
  • 20
1

You need to add an object containing the callback functions and a function to register them:

var myApp = {};
(function(context) {
    var id = 0;

    var callbacks = {};

    context.next = function() {
        id++;
        doCallbacks('next');
        return id;
    };

    context.setCallback = function(event, f) {
        if(!callbacks[event] || !callbacks[event] instanceof Array) {
            callbacks[event] = [];
        }
        callbacks[event].push(f);
    }

    context.reset = function() {
        id = 0;
    }

    function doCallbacks(key /*, event */) {
        if(callbacks[key] && callbacks[key] instanceof Array) {
            for(var i=0; i < callbacks[key].length; i++) {
                callbacks[key][i](/*event*/);
            }
        }
    }
})(myApp);

And then you can call:

myApp.setCallback('next', function() {
    alert('hello');
});

working jsFiddle

working jsFiddle with event objects

You may need to tweak the check for an array a bit though, I don't know how to do it perfectly.

MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • Your `if` block in the `next` method never execute, because it is after `return` statement. –  May 11 '13 at 12:29