app utils wrapFunction function fn after before condition replace if i

 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
app.utils.wrapFunction = function(fn, after, before, condition, replace) {
if (!_.isFunction(after) && _.isObject(after)) {
before = after.before;
condition = after.condition;
replace = after.replace;
after = after.after;
}
var oldfn = replace || fn;
return function() {
var context = this,
result,
beforeresult;
if (_.isFunction(condition) && (condition.apply(context, arguments) === false)) {
return false;
}
if (_.isFunction(before)) {
beforeresult = before.apply(context, arguments);
}
if (beforeresult !== undefined && beforeresult.then) {
var args = Array.prototype.slice.call(arguments);
beforeresult.then(function(resolved) {
args.push(resolved);
result = oldfn.apply(context, args);
if(_.isFunction(after)){
after.apply(context, args);
// console.info("after callback fired")
}
});
} else {
result = oldfn.apply(context, arguments);
if(_.isFunction(after)){
after.apply(context, arguments);
// console.info("after callback fired")
}
}
return result;
}
}