jquery - Using $(this) inside custom jquery plugin options
I am writting custom jquery plugin and I wonder If there is a possibilty to use $(this) selector inside custom jquery pugin options. For example:
$("#myDiv").customPlugin({
fisrtProperty: $(this).attr('id'), //I want "$(this)" points to the "$('#myDiv')"
myCallback: function() {
alert($(this).attr('id')); //inside callback $(this) works fine because I pass it in call function
}
});
My test plugin:
;(function($) {
var pluginName = "customPlugin"; //to easy renaming
var defaults = {
firstProperty: null,
myCallback: null
}
var Plugin = function(element, options) {
var $elem = $(element),
obj = this, //plugin object
settings = $.extend({}, defaults, options);
$elem.click(function() {
if ($.isFunction(settings.myCallback)) {
settings.myCallback.call($(this)); //very important to pass $(this)
}
$(this).append(settings.firstProperty);
});
}
$.fn[pluginName] = function(options) {
return this.each(function() { //to preserve chaining
var element = $(this);
if (element.data(pluginName)) {
return; //quick ends if element stores data of pluginname
}
var plugin = new Plugin(this, options);
//stores plugin object in this element's data object
element.data(pluginName, plugin);
});
}
})(jQuery);






Cartoon Clouds
Mountains
Sunrise
Clouds
Green Clouds
None














Help