tags:

views:

152

answers:

2

How do I create a jQuery plugin so that I can use namespaces in my plugin ?

$("#id1").amtec.foo1();
$("#id1").amtec.foo2();

None of these seem to work.

(function($) {
    var amtec = {
        $.fn.foo1 : function(){ return this.each(function(){}); },
        $.fn.foo2 : function(){ return this.each(function(){}); }
        };

    })(jQuery);
(function($) {
    $.fn.amtec = function(){
        var foo1 = function(){ return this.each(function(){}); };
        var foo2 = function(){ return this.each(function(){}); };
        }
    })(jQuery);
+1  A: 
(function($){
  $.namespace = function(ns, functions){
    $.fn[ns] = function() {return this.extend(functions)};
  };
  $.namespace('$', $.fn); // the default namespace
})(jQuery);

So now you can have a plugin:

$.fn.func = function(){alert('plugin'); return this'};

and create plugins in a namespace:

$.namespace ('mynamespace', {
  func: function() {alert('namespaced plugin'); return this;},
  otherfunc: function() {return this.css('color', 'yellow');}
});

And if you do

$('div').func(); // alerts 'plugin' -- no namespace

But

$('div').mynamespace().func(); // alerts 'namespaced plugin'

And

$('div').mynamespace().func().$().func(); // alerts 'namespaced

plugin', then resets to the normal jquery and alerts 'plugin'

GSto
+2  A: 
(function($) {
    $.fn.amtec = function () {
        var jq = this;
        return {
            foo1: function(){
                return jq.each(function(){});
            },

            foo2: function(){
                return jq.each(function(){});
           }
       }
    };
})(jQuery);
Alexander Gyoshev
Alexander, error console in FireBug shows :this.each is not a function
MotionGrafika
I guess I messed things up - I've updated my answer.
Alexander Gyoshev
Thanks a lot Alexandar ! It does work but as $("#id1").amtec().foo1();and not as$("#id1").amtec.foo2();
MotionGrafika
well, I guess it's inevitable - because you need to preserve the `this` reference, and you cannot get it within an instantiated object.
Alexander Gyoshev