简体   繁体   中英

How to call function inside jquery plugin after plugin is initialised

I', creating my own jQuery plugin which can be assigned to more than one element in document. I want, on some events, to call a function inside plugin for that particular element, but everything is driving me crazy. Plugin, itself, works, but problem with external calling exists.

simple plugin:

(function ( $ ) {
    $.fn.myPlugin = function (options) {
        var settings = $.extend({
            someOption: ""
        }, options);
        return this.each(function () {
            _init();
            _load();
        });
        function _init() {
            //some action..
        }
        function _load() {
            //some action..
        }
    };
    $.fn.myPlugin.reload = function () {
        _load(); //or this._load();
    }
}( jQuery ));

and in html:

<div id="div1"></div>
<button id="button1">Click to reload</div>
<script>
    $(document).ready(function() {
        var A=$("div1").myPlugin({
            someOption:"someValue"
        });
        $("#button1").click(function(){
            A.reload();
        });
    });
</script>

return is always that _load() is undefined... Any idea will be really appreciated.

Youre returning before you define the functions, also _load cannot be accessed from the reload function if its not in a higher scope:

(function ( $ ) {
//function definitions:
    function _init() {
        //some action..
    }
    function _load() {
        //some action..
    }


 $.fn.myPlugin = function (options) {
     var settings = $.extend({
        someOption: ""
    }, options);

    return this.each(function () {
        _init();
        _load();
    });

};
$.fn.myPlugin.reload = function () {
    _load(); //
}
}( jQuery ));

Note that it can be accessed like this:

 $.myPlugin.reload();

Reload is not part of an myPlugin instance.

If you want to return a custom object for each instance do this:

 (function ( $ ) {
 $.fn.myPlugin = function (options) {
     var settings = $.extend({
        someOption: ""
    }, options);

     //function definitions:
    function _init() {
        //some action..
    }
    function _load() {
        //some action..
    }
    //iterate
    this.each(function () {
        _init();
        _load();
    });

   return {
     reload:_load,
   };
};
}( jQuery ));

Now you can do

$("test").myPlugin().reload();

A is holding a reference to a jQuery object and as such has all the methods of $.fn . But your reload is not a method of $.fn but of $.fn.myPlugin. If you fix this and take Jonas` answer into account then it should work;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM