Fisu Fisu - 20 days ago 5
Javascript Question

Calling a function inside a jQuery plugin from outside

I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the

underline()
function.

jsFiddle

jQuery plugin

(function($) {
"use strict";

$.fn.testPlugin = function(options) {

// Settings
var settings = $.extend({
newText : "Yabadabado"
}, options);

return this.each(function(i, el) {

var init = function(callback) {
if( $(el).attr("class") === "red" ) {
$(el).css("color","red");
}

$(el).text(settings.newText);

if( callback && typeof(callback) === "function" ) {
callback();
}
};

var underline = function() {
$(el).addClass("underline");
};

init();
});
};

}(jQuery));


Assign the plugin to selectors

var doTest = $("#testItem").testPlugin({
newText: "Scoobydoo"
});

var doNewTest = $("#newTestItem").testPlugin({
newText: "kapow!"
});


Call a function that is located within the plugin

$("#underline").click(function(e) {
e.preventDefault();
doTest.underline();
});

Answer

Take a look at closures.

Here is a basic example of what a closure looks like in a jQuery plugin.

$.fn.plugin = function() {

    return {
        helloWorld: function() {
            console.log('Hello World!');
        }
    }
};

// init plugin.
var test = $('node').plugin();

// call a method from within the plugin outside of the plugin.
test.helloWorld();

You can see another example at the following jsfiddle.

http://jsfiddle.net/denniswaltermartinez/DwEFz/