Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing this's context to a plugin

How would i go about passing the context of $(this) to a plugin?

Currently, i have a plugin(code as shown below)

(function($) {
  $.fn.slides={
    slideIn:function(){
      $(this).fadeIn().slideDown();
    },
    slideOut:function(){
      $(this).fadeOut().slideUp();
    }
  }
})(jQuery);

Whenthe plugin is called via

$('h1').click(function(){
  $(this).slides.slideOut();
});

i get an error

Uncaught TypeError: Cannot read property 'defaultView' of undefined

because the context of this, is not passed correctly to the plugin's slideOut() method.I.e the slideOut's this context is that of the object $.fn.slides.

Apart from using .call() to pass the context,i.e

$('h1').click(function(){
  $(this).slides.slideOut.call(this);
});

is there any other way to pass the this context correctly to slideOut(), or anyway to structure my plugin so that i can call the method slideOut() via

 $('h1').click(function(){
      $(this).slides.slideOut();
    });

?

Thanks!

like image 605
Kenneth .J Avatar asked Oct 02 '22 00:10

Kenneth .J


1 Answers

Something like this would look more like a jQuery plugin:

(function ($) {
    $.fn.slides = function(method) {

        var methods = {
            slideIn: function () {
                $(this).fadeIn().slideDown();
            },
            slideOut: function () {
                $(this).fadeOut().slideUp();
            }
        };

        return this.each(function() {
            methods[method].call(this);
        });
    };
})(jQuery);

Usage:

$('h1').click(function() {
    $(this).slides('slideOut');
});

Also note that jQuery plugin should return a jQuery instance collection to make chainable possible.

Demo: http://jsfiddle.net/cC8fF/

like image 59
dfsq Avatar answered Oct 03 '22 13:10

dfsq