I’m starting a new Backbone app, and I’ve been quite fond of the javascript class inheritance system of Sencha Touch 2.0, basically i want to be able to do this :
Helium.define('Application', {
namespace: 'Helium',
constructor: function() {
console.warn('Helium');
}
});
Helium.define('Application', {
namespace: 'MyApp',
extend: 'Backbone.Events',
routers: ['Cards'],
constructor: function() {
console.warn(this);
this.callParent();
console.warn('MyApp');
//console.warn(Helium.getDisplayName(arguments.callee));
}
});
I’m stuck on the prototype chain definition (to make the this.callParent() work) :
var p = Object.create(extend);
var o = _.extend(p, data);
/*function() {
var _o = _.extend(p, data);
_o.constructor.apply(o, arguments);
return _o;
};*/
o.prototype.superclass = p;
o.prototype.callParent = function() {
console.warn(p);
};
Here is the complete micro-implementation so far :
So far, i have done this :
_.mixin({
resolve : function(path, base, separator) {
var parts = path.split('.' || separator),
key = parts.pop();
base = base || window;
while (parts.length) {
part = parts.shift();
base = base[part] = base[part] || {};
}
base[key] = base[key] || {};
return base[key];
}});
Helium = {
define: function(className, data) {
var base = window,
extend = data.extend || {constructor : function() {}},
namespace = data.namespace || null;
if(namespace) {
window[namespace] = window[namespace] || {};
base = window[namespace];
}
if(_.isString(extend)) extend = _.resolve(extend);
if(!extend) throw 'Extend error';
var parts = className.split('.'),
key = parts.pop();
while (parts.length) {
part = parts.shift();
base = base[part] = base[part] || {};
}
delete data.extend;
//delete data.namespace;
data.$name = key;
data.$className = className;
var p = Object.create(extend);
var o = _.extend(p, data);
/*function() {
var _o = _.extend(p, data);
_o.constructor.apply(o, arguments);
return _o;
};*/
o.prototype.superclass = p;
o.prototype.callParent = function() {
console.warn(p);
};
},
getDisplayName: function(callee) {
console.warn('getDisplayName', [this, arguments]);
console.warn(callee.toString());
}
};
I see what you’re going for here but if your end game is really being able to call the parent constructor I think it’s a little convoluted to try and impose Sencha’s inheritance model on Backbone because it is so simple and lightweight and ultimately it has its own inheritance implementation.
Since Backbone’s
extend()only exists on Backbone classes I think this is a good resource. Unless I’m misunderstanding you I think something along the lines ofMyApp.__super__.initialize()in Backbone would be roughly equivalent tothis.callParent()in Sencha Touch.