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;
}
}