ChiefORZ
ChiefORZ

Reputation: 90

Only callback if calling the same object

I am trying to incorporate a check if the Callback Function is a Call to the same Object.

I've made a rough Sketch for my Friend (because he isn't into JS), that he unsderstood pretty well.

function foo(callback){
    if(callback === foo) callback.call();
}
foo(function(){
    foo()
});

So I will check if the callback within the given prarmeters is the same Function (self executing?). In the first instance i thought i could just check if the called Function is an instance of the Object. Because I'm working with Object constructors. (if( newfoo instanceof foo )) But it turns out the called Function is an IIFE and the type of the Callback is an Function instead of an Object.

I've made up an Javascript Example that covers my Situation pretty well.

(function(){
    foo = function(){
        // Here are Private Functions within this Object
        return{
            bar: function(callback){
                if(typeof callback !== "undefined" && typeof callback === "function") callback(); // && if callback === object constructor
            }
        }
    }
}(this));


var Foo = new foo();
Foo.bar(function(){
    Foo.bar(function(){ // This Callbacks should be executed
        alert('Callback got called!'); // But the Callback that is no instance of 'Foo' should not be executed!
    });
})

I hope i have explained it good enough. And Hopefully someone can help me out.

Thanks!

Upvotes: 2

Views: 77

Answers (1)

dfsq
dfsq

Reputation: 193271

You are trying to solve very strange problem, however it's still possible to make it work. Technically you want to invoke only those callbacks that has Foo.bar invocation inside anywhere. In this case you can get function sourse code with toString() method and simple check it with regular expression. Something like this:

(function () {

    function hasOwnFunction(callback) {
        return /\.bar\(/.test(callback.toString());
    }

    this.foo = function () {
        // Here are Private Functions within this Object
        return {
            bar: function (callback) {
                if (typeof callback === "function" && hasOwnFunction(callback)) callback();
            }
        }
    }
}(this));


var Foo = new foo();
Foo.bar(function () {
    alert('I should be called 1');
    Foo.bar(function () {
        alert('I should be called 2')
        Foo.bar(function () {
            alert('Should not be called');
        })
    });
});

Also note that the only way for callback to be an instance of Foo is situation Foo.bar(Foo.bar). only then it makes sense to compare callback === this.bar. However this is not what you want of course, because it will lead to infinite recursion.

Upvotes: 1

Related Questions