app object creation

Create a namespaced object and inherit a destroy method.

by chovy

JavaScript

app = window.app || {};

_.extend(app, {
    destroy: function(){
        console.log('app.destroy called');
    },
    
    create: function(namespace, object) {
        app[namespace] = window.app[namespace] = {};
        
        if ( !object.destroy ) {
            _.extend(object, { destroy: this.destroy });
        }
        
        _.extend(app[namespace], object, { ns: namespace });
    }
});


app.create('foo', {
    init: function(){
        console.log('app.foo.init called');
    },
    
    destroy: function(){
        console.log('app.foo.destroy called');
        app.destroy();        
    }
});

app.create('bar', {
    init: function(){
        console.log('app.bar.init called');
    }
});

app.foo.init();
app.foo.destroy();
app.bar.init();
app.bar.destroy();