-
-
Save bradenpowers/1207520 to your computer and use it in GitHub Desktop.
Monkey patch for require in Titanium Mobile
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
/* | |
add a monkey-patched "require" function to the global scope (global object). | |
It is smarter in two ways: | |
- It only loads a module once | |
- If the exports object contains a function matching the module base name, return that | |
value from "require" - this is a bit of sugar added because Titanium's require implementation | |
does not allow you to replace the "exports" object directly | |
*/ | |
//monkey patch "require" in the global scope | |
require('require_patch').monkeypatch(this); | |
//regular modules are the same... | |
var module = require('module'); | |
module.sayHello('Marshall'); | |
module.sayGoodbye('Kevin'); | |
//modules which contain a type by the same name as the module... | |
var Person = require('Person'); | |
var jedi = new Person('Luke','Skywalker'); | |
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
exports.sayHello = function(name) { | |
alert('Hello '+name+'!'); | |
}; | |
exports.sayGoodbye = function(name) { | |
alert('Goodbye '+name+'!'); | |
}; |
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
exports.Person = function(firstName,lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
}; |
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
exports.monkeypatch = function(object) { | |
var scriptRegistry = {}, | |
old_require = object.require; | |
object.require = function(moduleName) { | |
if (!scriptRegistry[moduleName]) { | |
var mod = old_require(moduleName), | |
moduleRoot = moduleName.split(/[\/ ]+/).pop(); | |
if (typeof(mod[moduleRoot]) === 'function') { | |
scriptRegistry[moduleName] = mod[moduleRoot]; | |
} | |
else { | |
scriptRegistry[moduleName] = mod; | |
} | |
} | |
return scriptRegistry[moduleName]; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment