Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created November 23, 2011 21:59

Revisions

  1. robotlolita created this gist Nov 23, 2011.
    51 changes: 51 additions & 0 deletions multiple-delegation.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@

    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