Structuring clean Javascript

Status
You're currently viewing only tinyMan's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
I'm a fan of Revealing Module Pattern:

Code:
var MyModule = (function() {

  // "private" variable -- inaccessible outside of the closure
  var skipText = "skipping";

  // "private" method -- not exported in the return statement below
  function privateSkip() {
    return skipText;
  }

  function dance() {
    return "dancing";
  }

  function skip() {
    // Call a "private" method in the closure
    return privateSkip();
  }

  return {
    dance: dance,
    skip: skip
  };
})();

I find that this is easy (for me) to read, explicitly defines the "public" vs "private" methods, doesn't have any impact to calling methods and usually lets you skip dropping 'this's all over the place.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
[url=http:/civis/viewtopic.php?p=25455253#p25455253:3dk5wmhf said:
KallDrexx[/url]":3dk5wmhf]2nd to last time I tried to write modular javascript I got burned by scoping.

Last time I tried to remedy that by having the "public" function call a nested function using javascript's .call(module) to make sure things were scoped correctly. Not sure that's a good practice though but at least it made my life just a tiny bit less frustrating.

I'm not too sure where you would require the use of .call() with a well constructed set of javascript modules? Was this dealing with event callbacks (onClick handlers?) or in some other context? Have an example?
 
Status
You're currently viewing only tinyMan's posts. Click here to go back to viewing the entire thread.
Not open for further replies.