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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With