Created
April 21, 2013 20:21
-
-
Save tgvashworth/5430930 to your computer and use it in GitHub Desktop.
Managing Modularity – Code Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myModule = (function () { | |
// Private | |
var name = "AsyncJS"; | |
// Public | |
return { | |
getName: function () { | |
return name; | |
}, | |
setName: function (value) { | |
return (name = value); | |
} | |
}; | |
}()); | |
var sandbox = (function () { | |
return { | |
on: function (event, cb) { | |
// Register listener | |
}, | |
trigger: function (event) { | |
// Notify listeners | |
} | |
}; | |
}()); | |
var module = (function () { | |
// Event handler | |
var fn = function () { | |
// . . . | |
}; | |
return { | |
init: function (sandbox) { | |
// Get setup | |
sandbox.on('some-event', fn); | |
} | |
}; | |
}()); | |
define([ | |
'some', 'doodads' | |
], function (some, doodads) { | |
return Backbone.Model.extend({ | |
// . . . | |
}); | |
}); | |
define([ . . . ], function () { | |
// Mediator closure | |
return function sandboxify(mediator) { | |
// Sanbox constructor | |
return function Sandbox() { | |
// a new Sandbox & its methods | |
// have access to the mediator, | |
// but nothing else does! | |
}; | |
}; | |
}); | |
require(['sandboxify'], | |
function (sandboxify) { | |
var mediator = new Mediator(); | |
var Sandbox = sandboxify(mediator); | |
// . . . | |
var myModule = new myModule(new Sandbox()); | |
}); | |
var createSandbox = function () { | |
var sandbox = _.clone(Backbone.Events); | |
sandbox.request = function (identifier, cb) { | |
// Serve provision back to caller | |
// . . . | |
}; | |
sandbox.provide = function (identifier, provision) { | |
// Register a provision | |
// . . . | |
}; | |
return sandbox; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment