[livejournal] r23368: LJSUP-14377: Refactor LiveJournal hooks....
Committer: vvasin
LJSUP-14377: Refactor LiveJournal hooks.U trunk/htdocs/js/livejournal.js
Modified: trunk/htdocs/js/livejournal.js
===================================================================
--- trunk/htdocs/js/livejournal.js 2012-11-27 03:48:54 UTC (rev 23367)
+++ trunk/htdocs/js/livejournal.js 2012-11-27 07:58:57 UTC (rev 23368)
@@ -1,36 +1,78 @@
// This file contains general-purpose LJ code
-LiveJournal = {
- hooks: {} // The hook mappings
-};
+var LiveJournal = {};
-LiveJournal.register_hook = function (hook, func) {
- if (! LiveJournal.hooks[hook]) {
- LiveJournal.hooks[hook] = [];
- }
+// Hooks
+;(function ($) {
+ 'use strict';
- LiveJournal.hooks[hook].push(func);
-};
+ LiveJournal.hooks = {}; // The hook mappings
-// args: hook, params to pass to hook
-LiveJournal.run_hook = function () {
- //console.log('run_hook', arguments);
+ /**
+ * Register handler for hook
+ * @param {String} hook Hook name
+ * @param {Function} func Hook handler
+ */
+ LiveJournal.register_hook = function (hook, func) {
+ if (typeof hook !== 'string' || typeof func !== 'function') {
+ throw new Error('Provide correct hook name or handler.');
+ }
- var hookfuncs = LiveJournal.hooks[arguments[0]];
- if (!hookfuncs || !hookfuncs.length) {
- return;
- }
+ if ( !LiveJournal.hooks[hook] ) {
+ LiveJournal.hooks[hook] = [];
+ }
- var hookargs = [].slice.call(arguments, 1);
+ LiveJournal.hooks[hook].push(func);
+ };
- var rv = null;
+ /**
+ * Run registered hooks
+ * @param {String} hook Hook name
+ */
+ LiveJournal.run_hook = function (hook /**, args*/) {
+ var hookFuncs = LiveJournal.hooks[hook],
+ args = null,
+ result = null;
- hookfuncs.forEach(function (hookfunc) {
- rv = hookfunc.apply(null, hookargs);
- });
+ // nothing has been registered for this hook
+ if ( $.type(hookFuncs) !== 'array' || hookFuncs.length === 0 ) {
+ return;
+ }
- return rv;
-};
+ // arguments to pass for the hook
+ args = Array.prototype.slice.call(arguments, 1);
+ hookFuncs.forEach(function (hookFunc) {
+ result = hookFunc.apply(null, args);
+ });
+
+ return result;
+ };
+
+ /**
+ * Remove hook functionality
+ * @param {String} hook Hook name
+ * @param {Function} [func] Hook function to remove
+ */
+ LiveJournal.remove_hook = function (hook, func) {
+ if (typeof hook !== 'string') {
+ throw new Error('Hook name should be provided.');
+ }
+
+ // if no hooks has been registered yet
+ if (!LiveJournal.hooks[hook]) {
+ return;
+ }
+
+ if (typeof func === 'function') {
+ LiveJournal.hooks[hook] = LiveJournal.hooks[hook].filter(function (hookFunc) {
+ return hookFunc !== func;
+ });
+ } else {
+ LiveJournal.hooks[hook] = [];
+ }
+ };
+}(jQuery));
+
LiveJournal.initPage = function () {
//LJRU-3137: The code relies on the Site global variable
//so it appears on all livejournal pages. If it's
