lundi 28 septembre 2015

Better way to build javascript modules?

Can I get a little advice on my js modules? I'm good with js, but not quite guru status :) Am I refactoring my modules right?

I've been using the js module pattern like this (rough example, I'm just worried about the structure):

sloppy way?

/* Module Code */
var MapModule = (function ($) {
    var $_address;
    var $_mapContainer;

    function loadApi() {
        // do something. maybe load an API?
    }

    function someInternalMethod() {
        // do other things
    }

    var pub = {};
    pub.setAddress = function (address) {
        $_address = address;
    };
    pub.getAddress = function () {
        return $_address;
    };
    pub.initialize = function () {
        loadApi();
    }
})(jQuery);

// usage
MapModule.initialize();

But that usage seems a little sloppy. I like constructors.

I refactored some modules like this:

Better way?

(function ($) {
    this.MapModule = function () {
        var $_address;
        var $_mapSelector;
        var $_mapContainer;
        function loadApi() {
            // do something. maybe load an API?
        }
        function someInternalMethod() {
            $_mapContainer = $($_mapSelector);
            // do stuff with the jQ object.
        }

        var pub = {};
        pub.setAddress = function (address) {
            $_address = address;
        };
        pub.getAddress = function () {
            return $_address;
        };
        pub.initialize = function (selector) {
            $_mapSelector = selector;
            loadApi();
        }
    }
})(jQuery);

var map = new MapModule();
map.initialize('#mapcontainer');

That usage seems a lot cleaner to me, and it works just fine, but am I going about it properly?

Taking it another step

Say this module does some stuff with a div that wraps Google Maps and jQuery functionality: Any tips on turning that into a jQ plugin so I can use it with a signature like var map = $('mapcontainer').mapModule();

Thanks!

Aucun commentaire:

Enregistrer un commentaire