Wednesday, March 5, 2008

Joose has Roles / Traits

A direct translation of the Synopsis from Moose::Role looks like this:

Class("Eq", {meta: Joose.Role});
requires("isEqual");

methods({
notEqual: function (para) {
return !this.isEqual(para)
}
})

Class("Currency");
does(Eq)
has("value", {is: rw})

methods({

initialize: function (value) {
this.setValue(value)
},

isEqual: function (cur) {
return this.getValue() == cur.getValue()
}
})

check()


The check() makes a "compile time" check of the role requirements. This might later be implemented as an onload-event in browsers.

Joose.Roles are themselves implemented as Joose.Classes. The source looks like this:


Class("Joose.Role");
isa(Joose.Class);
has("requiresMethodNames")
methods({

initialize: function () {
this.name = "Joose.Role"
this.requiresMethodNames = [];
},

addRequirement: function (methodName) {
this.requiresMethodNames.push(methodName)
},

exportTo: function (classObject) {
classObject.meta.importMethods(this.getClassObject())
},

hasRequiredMethods: function (classObject) {
var complete = true
this.requiresMethodNames.each(function (value) {
var found = classObject.meta.can(value)
if(!found) {
complete = false
}
})
return complete
},

isImplementedBy: function (classObject) {

var complete = this.hasRequiredMethods(classObject);

if(complete) {
complete = this.implementsMyMethods(classObject);
}
return complete
}
})
Post a Comment