Geeks With Blogs

News Infragistics JQuery Advertisement
----------------
profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers

Check out Elapser from T3rse!
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
And then listen to Francis Chan speaking at LifeLight in SD.
Programming and Learning from SD

See John Papa's article for more information on the revealing pattern.

See http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript for a great reference as well.

I was trying to expose a property in my JavaScript object and setting it from an outside caller. When I ran the code, the value didn’t change. This held me up for awhile yesterday. When I Googled, GoodSearched the problem today, I found a question on Stackoverflow that was similar and lead me in the right direction. You need a setter, makes sense now ("It's all about scope" as a co-worker put it). So I put together a quick test in my JsFiddle example. Here’s a copy from the example. I also have an example without the initial instantiation and as a Knockout view model in the fiddle.

var bike = (function () {
  var isMoving = false,
    isMovingSetter = function (value) {
      isMoving = value;
    },
    test = function () {
      console.log('The bike is moving? ' + isMoving);
    };
  return {
    IsMoving: isMoving,
    Test: test,
    IsMovingSetter: isMovingSetter
  };
}());

// directly setting the property doesn't change the value, this tripped me up for awhile
bike.IsMoving = true;
console.log(bike.IsMoving);
bike.Test();

// a setter is necessary
bike.IsMovingSetter(true);
bike.Test();

Addendum:

Getters are required as well. This question from SO answers it pretty well.

I created a jsFiddle that shows the problem, then I added the getter and access it that way.

Posted on Tuesday, January 15, 2013 8:31 AM JavaScript | Back to top


Comments on this post: Setting a var property in the JavaScript Revealing Module Pattern requires a setter and a getter

# re: Setting a var property in the JavaScript Revealing Module Pattern requires a setter
Requesting Gravatar...
The code you have written is too much informative and helpful for me. Thanks for sharing it.
Left by Ian Harvey on Jan 21, 2013 2:40 AM

# re: Setting a var property in the JavaScript Revealing Module Pattern requires a setter and a getter
Requesting Gravatar...
I tried using your code and it didn't work the first time. However, I went over it with a fine tooth comb and realised I made a few typo's.

Anyway it works now and is really good. Will leave more feedback once I use it more.

Thanks
Left by Tommy Part on Feb 14, 2013 11:07 AM

Your comment:
 (will show your gravatar)
 


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free