Skip to content

Instantly share code, notes, and snippets.

@rblalock
Created October 21, 2011 20:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rblalock/1304879 to your computer and use it in GitHub Desktop.
Save rblalock/1304879 to your computer and use it in GitHub Desktop.
Simple inheritance with CommonJS Modules and Titanium Part 2
// Create the module
var controllerModule = require('dashboardController').boot(_params);
// Test to see if the parent controller's load method or dashboardController method fires
controllerModule.load();
// Test to see other properties
Ti.API.info(controllerModule.works);
/**
* Core Controller / Parent Object
*/
// Private
Ti.API.info('Parent controller constructor fired');
// Controller Methods
var api = {
load: function() {
Ti.API.info('Parent load method just fired');
},
build: function() {
Ti.API.info('Parent build method just fired');
},
getWindow: function() {
Ti.API.info('Parent getWindow method just fired');
},
works: false
};
// Main Controller
function Controller(args) {
// Assign args object or empty literal
var _args = args || {};
// Loop through api and assign member props / objects to this object
for(var prop in api) {
// Use sub-controller's object or if not there use super's
this[prop] = _args[prop] || api[prop];
}
};
// Public
exports.extend = function(args) {
var _args = args || {};
Controller.apply(this, [args]);
return this;
};
/**
* Dashboard2 controller
*/
// Private
var api = require('modules/core/controller').extend({
load: function() {
Ti.API.info('Child load method fired');
},
getWindow: function() {
Ti.API.info('Child getWindow method fired');
},
works: true
});
// Public
exports.boot = function(_params) {
// expose the public api object
return api;
};
@rblalock
Copy link
Author

Reference first example here - https://gist.github.com/1304879

@quochuy
Copy link

quochuy commented Mar 12, 2012

You could also do
parentModule.js

function foo() {
    ...
}
exports.foo = foo;

function foo2() {
    ...
}
exports.foo2 = foo2;

subModule.js

var parent = {};

function boot(app) {
    parent = require(app.getProperty('controllersPath') + '/controllerPrototype');
    for(var prop in parent) {
        if(!exports[prop]) {
            exports[prop] = parent[prop];
        }
    }
}
exports.boot = boot;

// Overriding foo2()
function foo2() {
    ...
    // call the parent function if needed.
    parent.foo2();
}
exports.foo2 = foo2;

// Local function
function foo3() {
    ...
}
exports.foo3 = foo3;

implementation.js

var subModule = require('subModule');
subModule.boot();
subModule.foo2();
subModule.foo3();

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