Don't use the Revealing Module Pattern. Many people learn the Revealing Module Pattern from Addy Osmani's book without paying attention to Addy's warning.
As you've found out, when you reveal your closured variables to other modules, they cannot be changed. That's a fundamental weakness of the Revealing Module Pattern. You probably did something like this
var mouse = (function(){
var x = 10, y = 20;
var drawLineTo = function(x1,y1){
console.log("Drawing line from " + x + "," + y + " to " + x1 + "," + y1);
};
return {
x: x,
y: y,
draw: drawLineTo
}
})
mouse.x = 50
mouse.draw(15,15) // print "Drawing line from 10,20 to 15,15"
and found that changing mouse.x
doesn't change the value of x
in the closure. While you can get around this by defining explicit getters and setters like so
var mouse = (function(){
var x = 10, y = 20;
var getX = function() {return x};
var setX = function(val) {x = val};
var drawLineTo = function(x1,y1){
console.log("Drawing line from " + x + "," + y + " to " + x1 + "," + y1);
};
return {
getX : getX,
setX : setX,
y: y,
draw: drawLineTo
}
})
mouse.setX(50);
mouse.draw(15,15) // print "Drawing line from 10,50 to 15,15"
That's just a stupid price to pay for using the Revealing Module Pattern. Much simpler is
var mouse = (function(){
// put your private variables and methods here.
return {
x : 10,
y: 20,
draw: function(x1,y1){
console.log("Drawing line from " + this.x + "," + this.y + " to " + x1 + "," + y1)
}
}
})
mouse.x = 50;
mouse.draw(15,15) // print "Drawing line from 50,20 to 15,15"
The key is to never reveal -- only put the things you intend to hide into the closure. Things intended to be public should be created as such.