Search code examples
javascriptjqueryfunctionprivatedeferred

Using deferred objects with private dynamic calling functions (Revealing pattern)


I'm trying to use jQuery deferred with private dynamic calling functions like this:

var module = (function(){
    var privateFuncs = {
        privateMethod: function(val) {
            console.log(val);
        }
    };

    var success = function() {
        console.log('Success');
    };

    var publicMethod = function() {
        var functionString = "privateMethod";
        privateFuncs[functionString]('test').done(function(){
           success();
        });
    };

    return {
        init: publicMethod
    };
})();

module.init();

And I'm getting this error:

privateFuncs[functionString](...) is undefined

http://jsfiddle.net/cbelizon/pTaze/1/

Is there any chance to achieve what I'm looking for?

Without the use of deferred objects, the code works like a charm, as you can see here:

JavaScript, call private function as a string inside public method without using eval (Revealing pattern)

Thanks!

EDIT:

Here's my new code:

var module = (function(){
    var privateFuncs = {
        privateMethod: function(val) {
            console.log(val);
        }
    };

    var success = function() {
        console.log('Success');
    };

    var publicMethod = function() {
        var functionString = "privateMethod";
        var deferred = $.Deferred(privateFuncs[functionString]('test'));
        deferred.done(function(){
           success();
        });
    };

    return {
        init: publicMethod
    };
})();

module.init();

The problem is that nothing happens when I create the deferred object, look at here:

http://jsfiddle.net/cbelizon/pTaze/3/


Solution

  • This is not the correct use of jQuery.Deferred:

    var module = (function(){
        var privateFuncs = {
            privateMethod: function(val) {
                console.log(val);
            }
        };
    
        var success = function() {
            console.log('Success');
        };
    
        var publicMethod = function() {
            var functionString = "privateMethod";
            var deferred = $.Deferred(function(defer) {
                privateFuncs[functionString]('test');
                defer.resolve()
            });
            deferred.done(function(){
               success();
            });
        };
    
        return {
            init: publicMethod
        };
    })();
    
    module.init();