lundi 6 juin 2016

Define multiple instances of Module (pattern) in JavaScript

I am trying to find best way how to create multiple instances and configure my module according Module pattern.

Currently I have

var Logger = (function () {
    // Private members
    var _settings = {
        json: JSON,
        output: console
    };
    // Private methods
    var _log = function (info) {
        _settings.output.log(info);
    };
    var _dump = function (info) {
        _log(_settings.json.stringify(info));
    };
    // Change default settings
    var changeSettings = function (settingsArgs) {
        if (settingsArgs !== undefined) {
            if (settingsArgs.json !== undefined) {
                _settings.json = settingsArgs.json;
            }
            if (settingsArgs.output !== undefined) {
                _settings.output = settingsArgs.output;
            }
        }
    };
    return {
        init: changeSettings,
        log: _log,
        dump: _dump
    };
})();

I have several questions about this pattern.

  1. What is the best way to provide configuration to the module, I simply created setter for private settings fields, but I feel this is not the best way it can be implemented. Please suggest right approach.

  2. How to create multiple instances of my module. As I understood, module commonly used to encapsulate global objects and logic (like singletons), so most of time only one instances of module exists, but I need to have multiple instances. In my case this can be useful for example, I can create one logger ConsoleLogger another one will be AlertLogger the difference is output, but now I can only have one instance.

Please suggest the right way to follow, I have already read a lot of articles but haven't found answers to my questions. Thanks

Aucun commentaire:

Enregistrer un commentaire