Calling a local function using jQuery

I have a jQuery function as follows:

(function ($) {
    $.fn.autoSuggest = function (data, options) {
        function add_selected_item(data, num) {
            (function ($) {
                $.fn.autoSuggest = function (data, options) {
                    alert(data);
                }
            })(jQuery);
        }
    }
})(jQuery);

If I wanted to call a local function add_selected_item()from outside this function, how would I do it?

I tried:

$.autoSuggest.add_selected_item(data, opt);

But I get $.autoSuggestis undefined.

Continuing to learn the ropes with jQuery. I don’t know exactly how this can be done, if at all.

Thank!

+3
source share
2 answers

The best resource for creating a properly structured jQuery plugin is Plugins / Author Documentation . The part related to your post is the Namespacing section .

, add_selected_item , autoSuggest. , add_selected_item autoSuggest. undefined .

, jQuery. , " ":

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

:

$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

, :

(function($) {
    var methods = {
        init: function(data, options) {
            //put your init logic here.
        },
        add_selected_item: function(data, num) {
            //here your other method
        }
    };

    $.fn.autoSuggest = function(method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.autoSuggest');
        }
    };
})(jQuery);

. , . , .

0

:

$.extend({
  autoSuggest: function(){
    ...
  }
});

$.fn.autoSuggest = function(){
  ...
};
+2
source

Source: https://habr.com/ru/post/1782164/


All Articles