Reputation: 57176
How can I access the one of the chained functions in a plugin?
this is my plugin, in which I need to return an appended element on the document.
(function($){
$.fn.extend({
selection: function(options) {
var defaults = {
element: "selection"
}
var options = $.extend(defaults, options);
var o = options;
var $this = this;
$this.function_1 = function(object)
{
alert('function 1');
}
$this.function_2 = function(object)
{
alert('function 2');
}
$(document.body).append("<div class='element'>Loading</div>");
var element = $('.element');
return element;
}
});
})(jQuery);
It should alerts 'function 2' when the button is clicked but it returns error on firefox.
Below is my jsffiddle,
Upvotes: 0
Views: 45
Reputation: 171679
One approach is to add an argument to the plugin function to pass method as string. Basics are taken from jQuery plugin authoring docs:
(function($) {
var methods = {
function_1: function(object) {
alert('function 1');
},
function_2: function(object) {
alert('function 2');
}
};
$.fn.selection = function(method, options) {
return this.each(function(){
$(this).click(function() {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tooltip');
}
});
});
})(jQuery);
Then to call plugin method:
$('.chain-function').selection('function_2'/* optional options object*/);
DEMO: http://jsfiddle.net/dm3ft/1/
NOTE: It is important that you realize that this
inside the plugin function is the DOM element and not confuse it with this
being part of your class
Upvotes: 1
Reputation: 1969
You can also use jQuery.fn
$(document).ready(function(){
$('.chain-function').function_2();
});
(function($){
$.fn.function_2 = function(object){
alert("yay!");
var element = $("<div />").addClass("element").text("Loading");
element.appendTo( $(document.body) );
return element;
};
})(jQuery);
Upvotes: 0