public
Last active

AdaJS OOP Example

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
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');

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.