Last active
December 20, 2015 19:09
-
-
Save Jaben/6180861 to your computer and use it in GitHub Desktop.
Provides a convention of loading views in modules by looking for the moduleId or moduleIdView case-insensitive. Useful for TypeScript AMD style definition with exports.
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
define(['exports', 'durandal/system'], function(exports, system) { | |
var afterDash = function(str) { | |
var dashIndex = str.lastIndexOf("/", str.length - 1); | |
return str.substr(dashIndex + 1, str.length - dashIndex); | |
}; | |
var findPropCaseInsensitive = function(obj, propName) { | |
var propLower = propName.toLowerCase(); | |
for (var prop in obj) { | |
if (prop.toLowerCase() === propLower) { | |
return prop; | |
} | |
} | |
return null; | |
}; | |
/** | |
* Overwrites resolve object the default object instance for a module. | |
* If the module is a function, that function is called with `new` and it's result is returned. | |
* If the module is an export object (AMD), a function named '[moduleId]' or '[moduleId]View' created with 'new' and returned. | |
* If the module is an export object (AMD), a instance named '[moduleId]' or '[moduleId]View' is returned. | |
* If the module is an object, the instance is returned. | |
* @method resolveObject | |
* @param {object} module The module to use to get/create the default object for. | |
* @return {object} The default object for the module. | |
*/ | |
var conventionResolveObject = function(module) { | |
if (!system.isFunction(module)) { | |
var instance = module; | |
var moduleId = system.getModuleId(module); | |
var possibleExports = [afterDash(moduleId), afterDash(moduleId) + "View"]; | |
for (var pi = 0; pi < possibleExports.length; pi++) { | |
var prop = findPropCaseInsensitive(module, possibleExports[pi]); | |
if (system.isFunction(module[prop])) { | |
instance = new module[prop](); | |
break; | |
} else if (system.isObject(module[prop])) { | |
instance = module[prop]; | |
break; | |
} | |
} | |
if (instance !== module) { | |
system.setModuleId(instance, moduleId); | |
} | |
return instance; | |
} | |
return module; | |
}; | |
exports.install = function () { | |
var previousResolveObject = system.resolveObject; | |
// override system.resolveObject with our own implemention on install | |
system.resolveObject = function (module) { | |
module = conventionResolveObject(module); | |
return previousResolveObject(module); | |
}; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Place in the Durandal\Plugins directory.
In the main app startup add: