Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...