2015-04-23 15:42:05 +09:00
|
|
|
|
2015-04-27 10:10:52 +09:00
|
|
|
Telescope.callbacks = {};
|
2015-04-23 15:42:05 +09:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Add a callback function to a hook
|
|
|
|
* @param {String} hook - The name of the hook
|
|
|
|
* @param {Function} callback - The callback function
|
|
|
|
*/
|
2015-04-24 09:48:36 +09:00
|
|
|
Telescope.callbacks.register = function (hook, callback) {
|
2015-04-23 15:42:05 +09:00
|
|
|
|
|
|
|
// if callback array doesn't exist yet, initialize it
|
|
|
|
if (typeof Telescope.callbacks[hook] === "undefined") {
|
|
|
|
Telescope.callbacks[hook] = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
Telescope.callbacks[hook].push(callback);
|
2015-05-01 18:22:00 +02:00
|
|
|
};
|
2015-04-23 15:42:05 +09:00
|
|
|
|
2015-04-27 10:10:52 +09:00
|
|
|
/**
|
|
|
|
* Remove a callback from a hook
|
|
|
|
* @param {string} hook - The name of the hook
|
|
|
|
* @param {string} functionName - The name of the function to remove
|
|
|
|
*/
|
|
|
|
Telescope.callbacks.remove = function (hook, functionName) {
|
|
|
|
Telescope.callbacks[hook] = _.reject(Telescope.callbacks[hook], function (callback) {
|
|
|
|
return callback.name === functionName;
|
|
|
|
});
|
2015-05-01 18:22:00 +02:00
|
|
|
};
|
2015-04-27 10:10:52 +09:00
|
|
|
|
2015-04-23 15:42:05 +09:00
|
|
|
/**
|
|
|
|
* Successively run all of a hook's callbacks on an item
|
|
|
|
* @param {String} hook - The name of the hook
|
|
|
|
* @param {Object} item - The post, comment, modifier, etc. on which to run the callbacks
|
|
|
|
* @param {Boolean} async - Whether to run the callback in async mode or not
|
|
|
|
*/
|
2015-04-24 09:48:36 +09:00
|
|
|
Telescope.callbacks.run = function (hook, item, async) {
|
2015-04-23 15:42:05 +09:00
|
|
|
|
2015-05-01 18:22:00 +02:00
|
|
|
async = async || false; // default to sync
|
2015-04-23 15:42:05 +09:00
|
|
|
var callbacks = Telescope.callbacks[hook];
|
|
|
|
|
|
|
|
if (typeof callbacks !== "undefined" && !!callbacks.length) { // if the hook exists, and contains callbacks to run
|
|
|
|
|
|
|
|
if (async) { // run callbacks in async mode, without returning anything
|
2015-05-01 18:22:00 +02:00
|
|
|
|
2015-04-23 15:42:05 +09:00
|
|
|
if (Meteor.isServer) {
|
|
|
|
// use defer to avoid holding up client
|
|
|
|
Meteor.defer(function () {
|
|
|
|
// run all post submit server callbacks on post object successively
|
|
|
|
callbacks.forEach(function(callback) {
|
|
|
|
callback(item);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
} else { // else run callbacks in sync mode, and return the modified item
|
|
|
|
|
|
|
|
return callbacks.reduce(function(result, callback) {
|
|
|
|
return callback(result);
|
|
|
|
}, item);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-04-24 09:48:36 +09:00
|
|
|
} else { // else, just return the item unchanged
|
|
|
|
return item;
|
2015-04-23 15:42:05 +09:00
|
|
|
}
|
2015-05-01 18:22:00 +02:00
|
|
|
};
|