From d82993a647d6e6550feb6c122443f6b977eb6ca5 Mon Sep 17 00:00:00 2001 From: Micha Niskin Date: Wed, 18 Apr 2012 10:55:45 -0400 Subject: [PATCH] Added the $.ns().patch() method --- README.markdown | 14 ++++++++++++++ jquery.condom.js | 33 +++++++++++++++++++++++---------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/README.markdown b/README.markdown index 3029683..1a57d6d 100644 --- a/README.markdown +++ b/README.markdown @@ -48,6 +48,20 @@ $.ns('myNamespace').add({ }); ``` +### jQuery.ns().patch +Monkey-patches the given method(s), prepending the original, unpatched jQuery method to the arguments passed to the method when called. + +#### Example +```javascript +$.ns('myNamespace').patch({ + toggle: function(orig) { + console.log("this is the patched toggle method"); + // Call the unpatched method now, with the arguments the patched method + // was called with. + return orig.apply(this, $.makeArray(arguments).slice(1)); + } +}); +``` ### jQuery.ns().methods Return the available methods to the given namespace, this can be used to check if the namespace is defined previously. Useful when distributing your libraries that have common namespace names. diff --git a/jquery.condom.js b/jquery.condom.js index 5d24a7e..4258bb3 100644 --- a/jquery.condom.js +++ b/jquery.condom.js @@ -21,18 +21,31 @@ // Allows you to add methods ala jQuery.fn (useful to namespace premade plugins) nsfun.fn = methods[ns]; + // If `key` is an object val is ignored and `key` is returned. Otherwise, + // an object is returned with obj[key] set to `val`. + function asObj(key, val) { + var obj = $.type(key) == "object" ? key : {}; + if (obj !== key) + obj[key] = val; + return obj; + } + // Add a method. nsfun.add = function(fname, fn) { - var new_funcs = typeof fname == "object" ? fname : {}; - // One method. - if (new_funcs !== fname) - new_funcs[fname] = fn; - // Group of methods. - $.each(new_funcs, function(fname, fn) { - methods[ns][fname] = function() { - fn.apply(this, arguments); - return this; - }; + $.each(asObj(fname, fn), function(fname, fn) { + methods[ns][fname] = function() { return fn.apply(this, arguments) }; + }); + return this; + }; + + // Monkey-patch a jQuery instance method. + nsfun.patch = function(fname, fn) { + $.each(asObj(fname, fn), function(fname, fn) { + methods[ns][fname] = (function(orig) { + return function() { + return fn.apply(this, [orig].concat($.makeArray(arguments))); + }; + })($.fn[fname]); }); return this; };