Skip to content

@azer /gist:4136102
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
AdaJS OOP Example
var ada = require('ada'),
assert = require('assert');
/**
* DEFINING CLASSES W/ AK47
*/
function Person(firstName, lastName) {
var obj = ada({
firstName: firstName,
lastName: lastName
});
obj.fullName = ada(obj.firstName, obj.lastName, function(first, last){ // This is both a binding and a computable property. It'll be called when firstName and/or lastname changed for once and the returned value will be cached.
return first + ' ' + last;
});
obj.onChange = ada(obj.firstName, obj.lastName); // publish all changes on firstName and lastName to the subscribers of onChange.
return obj;
}
/**
* CREATING OBJECTS
*/
var john = Person('John', 'Lennon');
john.onChange(function(firstName, lastName){
console.log('John has been updated: ', firstName, lastName);
});
assert.equal( john.fullName(), 'John Lennon');
john.firstName('John Winston'); // sets name as "John Winston"
assert.equal( john.fullName(), 'John Winston Lennon');
/**
* SUBCLASSING
*/
function Speaker(firstName, lastName, company){ // extends Person
var obj = Person.apply(null, arguments),
fullName = obj.fullName; // this will be overrided below.
obj.company = ak47(company);
obj.onChange.subscribeTo(obj.company);
obj.fullName = ak47(fullName, obj.company, function(fullName, company){
return fullName + ', ' + company;
});
return obj;
}
var douglas = Speaker('Douglas', 'Crockford', 'Yahoo');
douglas.onChange(function(firstName, lastName, company){
console.log('Douglas has been updated: ', firstName, lastName, company);
});
assert.equal( douglas.fullName(), 'Douglas Crockford, Yahoo');
douglas.firstName('Dougl@s');
douglas.company('Paypal');
assert.equal( douglas.fullName(), 'Douglas Crockford, Paypal');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.