Last active
December 26, 2015 20:29
-
-
Save liyu1981/7209479 to your computer and use it in GitHub Desktop.
require wrapper with package names.
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
/* | |
This will intro clustertech flavour of require -- ctRequire. | |
Originally, require works as | |
require([ | |
'm1.js', | |
'm2.js', | |
'm3.js' | |
], | |
function(m1, m2, m3) { | |
}); | |
There is a serious problem that the callback argument list is in the same | |
order of dependency list. When code gets complex, this is not maintainable. | |
E.g., we want to intro 'm25.js' between 'm2.js' and 'm3.js', we have to modify | |
the callback function's argument list (to be 'm1, m2, m25, m3'). This is not | |
maintainable. | |
So our flavour require will work as | |
ctRequire([ | |
['m1', 'm1.js'], | |
'm2.js', | |
['m', 'm3.js'] | |
], | |
function(mm) { | |
// now you can use mm.m1 to access 'm1.js' | |
// mm.m2 to access 'm2.js' | |
// mm.m to access 'm3.js' | |
}); | |
In other words, we intro the package labels into requirejs. | |
*/ | |
(function(window) { | |
function _genMmap(d) { | |
var r = { map: {}, list: [] }; | |
d.forEach(function(e, index) { | |
if (typeof e === 'string') { | |
var l = e.split("/").slice(-1)[0].split(".")[0]; | |
r.map[index] = l; | |
r.list.push(e); | |
} else { | |
r.map[index] = e[0]; | |
r.list.push(e[1]); | |
} | |
}); | |
return r; | |
} | |
function _genMM(args, mmap) { | |
var al = args.length; | |
var mm = {}; | |
for (var index = 0; index < al; index++) { | |
mm[mmap.map[index]] = args[index]; | |
} | |
return mm; | |
} | |
window.ctRequire = function(dependency, callback) { | |
var mmap = _genMmap(dependency); | |
require(mmap.list, function() { | |
var mm = _genMM(arguments, mmap); | |
callback.apply(this, [mm]); | |
}); | |
}; | |
window.ctDefine = function(dependency, defunc) { | |
var mmap = _genMmap(dependency); | |
define(mmap.list, function() { | |
var mm = _genMM(arguments, mmap); | |
return defunc(mm); | |
}); | |
}; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment