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.

Upvotes: 0

Views: 2696

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

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();

Upvotes: 4

user1521685
user1521685

Reputation: 210

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;)

Upvotes: 0

Related Questions