Created
November 23, 2011 21:59
-
-
Save robotlolita/1390046 to your computer and use it in GitHub Desktop.
multiple delegation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var boo = require('boo') | |
var Delegate = { | |
// Makes the given property a getter, that will try the | |
// objects in order until it finds a suitable one. | |
// | |
// proxy :: String → Object | |
proxy: | |
function proxy(property) { | |
var local = "_" + property | |
Object.defineProperty(this, property, { | |
get: delegate_property | |
, set: function(value){ this[local] = value } | |
, configurable: true | |
, enumerable: true }) | |
return this | |
function delegate_property() { var i | |
if (local in this) return this[local] | |
if (!this.proto_list) return undefined | |
i = this.proto_list.length | |
while (i--) | |
if (property in this.proto_list[i]) | |
return this.proto_list[i][property] }} | |
} | |
var foo = { x: 1, z: 1 } | |
var bar = { y: 2 } | |
var baz = boo.clone(Delegate, { | |
proto_list: [foo, bar] | |
, _z: 2 | |
}) | |
baz.proxy('x').proxy('y').proxy('z') | |
console.log(baz.x, baz.y, baz.z) | |
// 1 2 2 | |
baz.proto_list = [] | |
console.log(baz.x, baz.y, baz.z) | |
// undefined undefined 2 | |
baz.proto_list = [foo, bar] | |
foo.y = 1 | |
console.log(baz.x, baz.y, baz.z) | |
// 1 2 2 -- bar still has a higher precedence :3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment