How do I access module variables using requireJS?

user759885 picture user759885 · Sep 16, 2012 · Viewed 8.2k times · Source

I have been using Javascript for a while and I have just tried using modules and requireJS for the first time and its hard to get my head around new design patterns!

Here is my first attempt:

require([
    "jquery",
    "testModule"
], function ($, testModule) {
    $(function () {
        var testInstance1 = testModule;
        testInstance1.setID(11);
        alert(testInstance1.id);
    });
});

and testModule.js

define([
  'jquery'
], function ($) {

    var id = 0;

    var setID = function (newID) {
        id = newID;
        return id;
    };
    return {
        setID: setID,
        id:id
    };
});

This returns 0 and I was expecting 11. What am I missing?

It is also a simplified example of course. I would like to create multiple objects and each should keep its own variables in state. For example if I wanted a module to append a list to a container DIV but also contain functions to add, clear or query data in that list how should I structure the module functions so that each implementation keeps its own state.

Thanks

Answer

Stephen picture Stephen · Sep 16, 2012

You actually aren't missing anything requireJS related here. The problem is that only objects are passed around by reference (and maybe arrays.. can't remember for sure right now). Numbers are not. So, when you returned {setID: setID, id: id}, the 'id' got set to the value of 'id', never again to be updated. What you want to do is use a function such as 'getID', which will reference the original variable, rather than the original variable's value:

return {
    setID: setID,
    getID: function () {return id;}
};

and then...

testInstance1.setID(11);
alert(testInstance1.getID());