My plugin takes some time doing something. So I want to listen to when the plugin is done with its task, from outside, so that I can display something.
I want to have something like this –
$('li').filterGroup ({
onInit: function(){
alert("plugin has started working");
},
onComplete: function(){
alert("plugin has finished");
}
})
I tried writing this inside my plugin code –
(function($) {
// jQuery plugin definition
$.fn.filterGroup = function(config)
{
var settings = {
//some settings defined here
};
var thisDropdown = this; //master copy
if(config)
{
$.extend(settings, config);
}
/*Tried following changes to make events work*/
/*Tried following changes to make events work*/
/*Tried following changes to make events work*/
//I tried the following – assuming I will be able to listen to an onComplete event from outside
// reference the function from the options passed
var theFunc = config.onInit;
var anotherFunc = config.onComplete;
theFunc.call(); //does not work - gives error "theFunc is not a function"
this.each(function()
{
//here my plugin logic is done
anotherFunc.call(); //this is also not working - "anotherFunc is not a function"
});
// allow jQuery chaining
return thisDropdown;
};
But this is not working, I am getting error –
theFunc is not a function
Note – I checked the PLugins authoring docs and specifically the events section http://docs.jquery.com/Plugins/Authoring#Events, but looks like that is for defining public functions which can be called from outside, so not what I am looking for. Where is the original jquery doc for this? I think I just need to follow the docs properly.
Also checked the following questions but not getting –
Bind Event to Custom Plugin Function in jQuery
Custom Event For Custom JQuery Plugin
Handle events in a jQuery plugin
Update
Okay, got my mistake, in my actual code I had theFunc.call() and anotherFunc.call() but in the calling part I had only handled onComplete. So, do I need to explicitly write the onInit() part in my plugin call –
This part –
onInit: function(){
alert("plugin has started working");
}
I mean if events are defined inside plugin, what if I don’t want to handle in the outside code?
Strange. It works for me.
http://jsfiddle.net/LHzjG/
BTW, you can also invoke the callbacks directly using
config.onComplete()and put params if u like. And you can usejQuery.isFunction()to check if it’s a function beforehand.