Skip to content

Instantly share code, notes, and snippets.

@Jaben
Last active December 20, 2015 19:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jaben/6180861 to your computer and use it in GitHub Desktop.
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.
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);
};
};
});
@Jaben
Copy link
Author

Jaben commented Aug 8, 2013

Usage

Place in the Durandal\Plugins directory.

In the main app startup add:

app.configurePlugins({ viewconvention:true });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment