-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathadvise.js
107 lines (102 loc) · 2.36 KB
/
advise.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
(function(factory){
if(typeof define != "undefined"){
define(["./dcl"], factory);
}else if(typeof module != "undefined"){
module.exports = factory(require("./dcl"));
}else{
advise = factory(dcl);
}
})(function(dcl){
"use strict";
var Node = dcl(null, {
//declaredClass: "dcl.Node",
constructor: function(){
this.nb = this.pb = this.na = this.pa = this.nf = this.pf = this;
},
a: function(b, a, f, o){
var t = new Node;
t.p = this;
t.b = b;
this._a("b", t);
t.a = a;
this._a("a", t);
t.f = f;
this._a("f", t, o);
t.o = o;
if(o){ t.f = o(t.pf.f); }
return t;
},
_a: function(topic, node, flag){
if(node[topic] || flag){
var n = "n" + topic, p = "p" + topic;
(node[p] = this[p])[n] = (node[n] = this)[p] = node;
}
},
r: function(node){
this._r("b", node);
this._r("a", node);
this._r("f", node);
},
_r: function(topic, node){
var n = "n" + topic, p = "p" + topic;
node[n][p] = node[p];
node[p][n] = node[n];
},
destroy: function(){
var f = this.pf.f, t = this.nf, p = this.p;
this.r(this);
if(t !== this){
for(; t !== p; f = t.f, t = t.nf){
if(t.o){
t.f = t.o(f);
}
}
}
}
});
Node.prototype.unadvise = Node.prototype.destroy; // alias
function makeAOPStub(x){
var f = function(){
var p, r, t = this, a = arguments;
// running the before chain
for(p = x.pb; p !== x; p = p.pb){
p.b.apply(t, a);
}
// running the around chain
try{
if(x.pf !== x){ r = x.pf.f.apply(t, a); }
}catch(e){
r = e;
}
// running the after chain
for(p = x.na; p !== x; p = p.na){
p.a.call(t, a, r);
}
if(r instanceof Error){
throw r;
}
};
f.adviceNode = x;
return f;
}
function advise(instance, name, advice){
var f = instance[name], a;
if(f && f.adviceNode && f.adviceNode instanceof Node){
a = f.adviceNode;
}else{
a = new Node;
if(f && f.advices){
f = f.advices;
a.a(f.b, f.a, f.f);
}else{
a.a(0, 0, f);
}
instance[name] = makeAOPStub(a);
}
if(advice instanceof Function){ advice = advice(name, instance); }
return a.a(advice.before, advice.after, 0, advice.around);
}
//advise.before = function(instance, name, f){ return advise(instance, name, {before: f}); };
//advise.after = function(instance, name, f){ return advise(instance, name, {after: f}); };
return advise;
});