2011-11-17 04:24:43 +00:00
|
|
|
exports.Hookable = Hookable;
|
|
|
|
|
|
|
|
function Hookable() {
|
|
|
|
// hookable class
|
|
|
|
};
|
|
|
|
|
2011-11-20 05:36:15 +00:00
|
|
|
Hookable.afterInitialize = null;
|
|
|
|
Hookable.beforeValidation = null;
|
|
|
|
Hookable.afterValidation = null;
|
|
|
|
Hookable.beforeSave = null;
|
|
|
|
Hookable.afterSave = null;
|
|
|
|
Hookable.beforeCreate = null;
|
|
|
|
Hookable.afterCreate = null;
|
|
|
|
Hookable.beforeUpdate = null;
|
|
|
|
Hookable.afterUpdate = null;
|
|
|
|
Hookable.beforeDestroy = null;
|
|
|
|
Hookable.afterDestroy = null;
|
2011-11-17 04:24:43 +00:00
|
|
|
|
2012-04-09 16:24:35 +00:00
|
|
|
Hookable.prototype.trigger = function trigger(actionName, work, data) {
|
2011-11-20 05:36:15 +00:00
|
|
|
var capitalizedName = capitalize(actionName);
|
|
|
|
var afterHook = this.constructor["after" + capitalizedName];
|
|
|
|
var beforeHook = this.constructor["before" + capitalizedName];
|
|
|
|
var inst = this;
|
|
|
|
|
|
|
|
// we only call "before" hook when we have actual action (work) to perform
|
2011-11-17 07:00:12 +00:00
|
|
|
if (work) {
|
2011-11-20 05:36:15 +00:00
|
|
|
if (beforeHook) {
|
|
|
|
// before hook should be called on instance with one param: callback
|
|
|
|
beforeHook.call(inst, function () {
|
|
|
|
// actual action also have one param: callback
|
|
|
|
work.call(inst, next);
|
2012-04-09 16:24:35 +00:00
|
|
|
}, data);
|
2011-11-20 05:36:15 +00:00
|
|
|
} else {
|
|
|
|
work.call(inst, next);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
2011-11-17 04:24:43 +00:00
|
|
|
|
2011-11-20 05:36:15 +00:00
|
|
|
function next(done) {
|
2012-04-18 23:20:44 +00:00
|
|
|
if (afterHook) {
|
|
|
|
afterHook.call(inst, done);
|
|
|
|
} else if (done) {
|
|
|
|
done.call(this);
|
|
|
|
}
|
2011-11-17 07:00:12 +00:00
|
|
|
}
|
|
|
|
};
|
2011-11-17 04:24:43 +00:00
|
|
|
|
2011-11-17 07:00:12 +00:00
|
|
|
function capitalize(string) {
|
|
|
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
|
|
}
|