How to use functions in plugin

Viewed 160

I am working on a JQuery plugin. I am quite confused with how to use this jQuery plugin. How can I call a jQuery plugin function outside the plugin?

Here is my plugin code:

(function ($) {
    function _setValue(self, value) {
        ....
    }

    //Other functions

    $.fn.inputpicker = function (method) {
        if (!this.length) return this;
        if (typeof method == 'object' || !method) {
            return methods.init.apply(this, arguments);

        }
        else if (methods[method]) {
            return methods[method].apply(this, 
            Array.prototype.slice.call(arguments, 1));
        }
        else { $.error("Method " + method + " does not exist on 
        jQuery.inputpicker"); }
    }

});

You can find the whole plugin here.

Now, How can I use _setValue function in my own codes?

2 Answers

Now, How can I use _setValue function in my own codes?

You can write:

$('#test').inputpicker('val', 'your string');

Call the inputpicker instance and on this pass the function and value.

The value needs to match one of the data attribute:

$('#test').inputpicker({
    data:[ "Text 1", "Text 2", "Text 3" ],
    autoOpen: true
});
$('button').on('click', function(e) {
    $('#test').inputpicker('val', this.textContent);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/ukalpa/inputpicker@master/src/jquery.inputpicker.css">
<script src="https://cdn.jsdelivr.net/gh/ukalpa/inputpicker@master/src/jquery.inputpicker.js"></script>


<input class="form-control" id="test" value="2" />
<button type="button">Text 1</button>
<button type="button">Text 2</button>
<button type="button">Text 3</button>

The function is tied to the plugin and behaves like a private method of an object. Hence you cannot access the function directly outside the plugin.

You can work around this by editing the plugin for example like this:

(function( $, document, window ) {

    function _setValue(self, value) {
        ....
    }

    // export the function to the global window object
    window.setValue = _setValue;
    ....

}( jQuery, document, window ));
Related