Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Chain Pattern with Self Revealing Module Pattern in JavaScript?

I have the below code:

filtersManager = (function ($) {

    var that = this;

    function configure() {

        // some work

        return that;
    };

    function process() {

       // some work

        return that;
    }    

    return {
        // public functions
        configure: configure,
        process: process
    };
}(jQuery));

but when it's called using the below it fails:

filtersManager.configure().process();

Error: Object doesn't support property or method 'process'

whereas the below works:

filtersManager.configure();
filtersManager.process();
like image 751
The Light Avatar asked Feb 17 '14 08:02

The Light


2 Answers

Immediate function is executed in global object (window) context. Try something similar to this:

filtersManager = (function ($) {

    var that = {};

    that.configure = function() {
        // some work
        return that;
    };

    that.process = function() {
        // some work
        return that;
    }

    return that;

}(jQuery));


UPD. Based on comments

Constructor pattern seems to fit your need better:

var FiltersManager = (function($) {

    function FiltersManager() {}

    FiltersManager.prototype = {
        configure: function() {
            console.log('configure');
            return this;
        },
        process: function() {
            console.log('process');
            return this;
        }
    }

    return FiltersManager;

}(jQuery));

new FiltersManager().configure().process();
like image 33
dfsq Avatar answered Sep 22 '22 06:09

dfsq


You are returning the wrong thing (this in a plain function invocation is the global object). You want to return the object that you originally created, which I will call the interface.

filtersManager = (function ($) {

    var interface = {
        // public functions
        configure: configure,
        process: process
    };

    function configure() {

        // some work

        return interface;
    };

    function process() {

       // some work

        return interface;
    }    

    return interface;
}(jQuery));

If you're wondering why I can reference the functions defined below, it's due to hoisting.

like image 56
alex Avatar answered Sep 23 '22 06:09

alex