dexteryy / NervJS

A tiny, pure, event-based model wrapper for the MVC or MDV (Model-driven Views) pattern
http://ozjs.org/NervJS/
2 stars 1 forks source link

关于NervJS的实现 #1

Open crossai-2033 opened 11 years ago

crossai-2033 commented 11 years ago

请教一下,看了下源码,由于依赖eventmaster没去更深入看。 NervJS set或remove都会fire change事件,这个理解。 但没能理解 _watchAll和_unwatchAll在源码中起到的作用,能否简单讲解一下?

v.observer.bind('change', this.observer.promise(k + ':update').pipe.fire)
                    .bind('change', this.observer.promise('change').pipe.fire);

主要是这段promise

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1617775-nervjs?utm_campaign=plugin&utm_content=tracker%2F227451&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F227451&utm_medium=issues&utm_source=github).
dexteryy commented 10 years ago

promise#pipe 是一系列语法糖,相当于:

var father = this;
child.observer.bind('change', function(subject, msg){
     father.observer.fire(k + ':update', msg);
});

_watchAll 和 _unwatchAll 的作用看这个例子:

var o = nerv({
    a: 1,
    b: nerv({
        c: 1
    })
});

o.observer.on('a:update', function(changes){
    console.info('a:update', changes.name, changes.newValue);
}).on('b:update', function(changes){
    console.info('b:update', changes.name, changes.newValue);
}).on('change', function(changes){
    console.info('o:change', changes.name, changes.newValue);
});

o.get('b').observer.on('c:update', function(changes){
    console.info('c:update', changes.name, changes.newValue);
});

o.set('a', 2);
o.get('b').set('c', 2);

o.set(function(o){
    o.b.set('c', 3);
    o.b.set('c', 4);
    o.b.set('c', 5);
    o.a = 5;
    o.d = 5;
    window.o2 = o;
});
console.info(o.data());

window.o2.a = 6;
console.info(o.data());

/* result:
a:update a 2
o:change a 2

c:update c 2
b:update c 2
o:change c 2

c:update c 3
c:update c 4
c:update c 5
o:change undefined undefined 
Object {a: 5, b: { c: 5 }, d: 5}

Object {a: 5, b: { c: 5 }, d: 5}
*/