I am developing a plugin, after add object to the plugin i want to call some events to same object from outside, how can i do that
(function ($, undefined) {
jQuery.fn.pluginname = function (options) {
var set = $.extend({
opacity: 0.5
}, options);
//if(options.type)
var cdiv = this;
cdiv.css("opacity",set.opacity);
function callthis()
{
cdiv.css("display","none");
}
}
})(jQuery);
jQuery("#first").pluginname({opacity:0.5});
jQuery("#second").pluginname({opacity:0.5});
// call this function later
jQuery("#first").pluginname("callthis");
The usual way is to have your plugin accept "methods" as string arguments, e.g.:
jQuery("#first").pluginname("callThis");
Internally in the plugin, you route that request to the function.
Normally you'd also want to store the options used initially somewhere other than just in the closure; data
is useful for that.
And you normally have a "destroy"
method to remove the plugin from elements.
So:
(function ($, undefined) {
var methods = {
init: function(options) {
// Determine options
var opts = $.extend({
opacity: 0.5
}, options);
// Remember them
this.data("pluginname", opts);
// Initial stuff
this.css("opacity", opts.opacity);
},
callThis: function(opts) {
// Use 'opts' if relevant
this.css("display","none");
},
destroy: function(opts) {
this.removeData("pluginame");
this.css("display", "").css("opacity", "");
}
};
jQuery.fn.pluginname = function (options) {
var method, args;
// Method?
if (typeof options === "string") {
// Yes, grab the name
method = options;
// And arguments (we copy the arguments, then
// replace the first with our options)
args = Array.prototype.slice.call(arguments, 0);
// Get our options from setup call
args[0] = this.data("pluginname");
if (!args[0]) {
// There was no setup call, do setup with defaults
methods.init.call(this);
args[0] = this.data("pluginname");
}
}
else {
// Not a method call, use init
method = "init";
args = [options];
}
// Do the call
methods[method].apply(this, args);
};
})(jQuery);
Live Example | Source
Try this:
(function ($, undefined) {
jQuery.fn.pluginname = function (options) {
var set = $.extend({
opacity: 0.5
}, options);
//if(options.type)
if(typeof options == function){
return function callthis()
{
cdiv.css("display","none");
}
} else{
return function(){
var cdiv = this;
cdiv.css("opacity",set.opacity);
}
}
}
})(jQuery);