I’m trying to add a define module method to my top-level namespace, which first defines the namespace. For example,
APP.define('modules.moduleName', function () {
return {name: 'Module 1' };
});
But it seems that with my implementation of it, there is an assignment problem. Here is a simplified example of my implementation.
var APP = APP || {};
APP.namespace = function( nsString ) {
var parts = nsString.split('.'),
parent = this,
i;
if (parts[0] === 'APP') {
parts = parts.slice(1);
}
for ( i = 0; i < parts.length; i++ ) {
if (typeof parent[parts[i]] === 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
// Simplified example of my define function
APP.define = function( name, definition ) {
var namespace = APP.namespace( name );
namespace = definition();
return namespace;
};
// Example Module
APP.define('modules.example', function () {
return {
name : 'Application',
module : 'APP.module'
};
});
However, it seems namespace is not assigned under the APP namespace after assigning it to definition(). However var module = APP.define('module.example', function () { /*...*/ }) works. This also works:
APP.define = function( name, definition ) {
var namespace = APP.namespace( name );
var module = definition();
for (var prop in module) {
if (module.hasOwnProperty[prop]) {
namespace[prop] = module[prop];
}
}
return namespace;
};
There must be something about object reference or callback scope I’m missing.
When you assign var namespace to APP.namespace( name ) you get last part of namespace by reference, but then that
namespace = definition()just redefines your namespace variable to result ofdefinitionfunction.You can merge your
APP.namespaceandAPP.defineso your pre-last parent assigns last part of namespace as property todefinitionfunctionThe code is: