How to create jQuery Element Methods with NameSpace

jquery, jquery-plugins

Solution

If you don't need to be compatible with IE8, you may use Object.defineProperty.

Working example :

 Object.defineProperty($.fn, 'namespace', {
  get: function(){
    var t = this;
    return {
      lowercasehtml: function(){
         return t.html(function(_,h){ return h.toLowerCase() }); 
      }
    }
  }
});

$('#a').namespace.lowercasehtml(); // changes the html of #a to lowercase (yes, it's stupid, I know)

Demonstration

But I'm not convinced it's a good idea to namespace like this. I would have simply defined

$.fn.namespace_lowercasehtml = function() ...

That's what I personally do for my application specific extensions to jQuery.

Problem

Suffice it to say, I'm wanting to branch my plugin writing a bit, and decided I want to be able to "namespace" them. So far, rewriting the `$.method` ones to `$.namespace.method` has been easy. The problem I'm having is making Element Methods such as `$('element').method()`, but to use a namespace; for example `$('element').namespace.method()`. I've tried a few workarounds and can create `$.fn.namespace.method`, however, when I call `this` from within that method, I only get `$.fn.namespace` and not the `'element'` that I'd like to get. Example: If i call `$('body').namespace.test()`, then inside method `test`, I want `this` to be the element `<body></body>` Any help figuring out how to pull this off much appreciated. Probably just over-thinking things as usual. Currently trying possible work-arounds for something like `$('body').namespace().method()`, thus far, not working so well ... :P

Original source