lesssugar
lesssugar

Reputation: 16181

Reusing private jQuery functions in another module

Background

I have my jQuery code organized in separate files, holding object literals like this (dummy) one:

$(function() {
    'use strict';

    // Example feature module
    function featureOne() {

        var privateVar = 0;

        function foo() {
            bar(privateVar);
        }

        function bar(n) {
            console.log(n);
        }

        return {
            foo: foo
        };

    }

    var myFeature = featureOne();
    myFeature.foo();
});

This way I expose only function foo(), so bar() and privateVar are private and not accessible from other modules.

Problem

Now, let's assume I need some of my private functions to be available for another module - featureTwo() - to serve as part of it, providing the exact same functionality. However, the two modules should stay separated from each other as they react to different events or depend on different factors. Basically, nothing except the "shared" code connects them.

What is the optimal/right way to achieve this? The goal is to avoid code repetition and keep things clean. I was thinking about moving the "shared" part of code out to the global scope but I have the feeling that's not the best way to go.

Any suggestions to organize the code properly are appreciated.

Upvotes: 0

Views: 65

Answers (1)

user3886234
user3886234

Reputation:

You could define a getter / setter, and name those functions with a preceding _ to indicate that they shouldn't be messed with:

$(function() {
    'use strict';

    // Example feature module
    var featureOne = (function() {
        var privateVar = 0;

        function bar(n) {
            console.log(n);
        }

        return {
            foo: function() {
                bar(privateVar);
                return this;
            },
            _getPrivateVar: function() {
                return privateVar;   
            },
            _setPrivateVar: function(val) {
                privateVar = val;
                return this;
            }
        }
    })()

    var myFeature = featureOne;
    myFeature.foo(); //logs 0
    console.log(myFeature._getPrivateVar()) //logs 0
    myFeature._setPrivateVar('hi').foo() //logs 'hi'
});

Upvotes: 1

Related Questions