How to implement jQuery plugin with this function?

So that it can be shown or hidden as follows:

$(selector).pluginName('show')
$(selector).pluginName('hide')

The problem is how can I find out which one to show or hide?

Now I do this:

$.fn.pluginName = function(opts) {  
    var conf = $.extend({},opts);
    return this.each(function() { 
        if(conf && 'conf' == conf.type)
        {
            //ClassName is defined elsewhere
            new ClassName(conf,$(this));
        }
        else
        {
            //**show or hide corresponding instance**
        }
    });
}
+3
source share
2 answers

You can use datato associate your object with the DOM element to which it belongs:

$.fn.pluginName = function(opts) {
  if(typeof(opts) == "string"){
    this.each(function(){
      // Get the associated obj
      var obj = $(this).data('ClassName');
      if(obj){
        if(opts == "show") obj.myShowMethod();
        else if (opts == "hide") obj.myHideMethod();
      }
    })
  } else {
    var conf = $.extend({},opts);  
    this.each(function() { 
      var obj = new ClassName(conf,$(this));
      // Associate your object with this DOM element
      $(this).data('ClassName', obj);
    });
  }
  return this; // Don't break the chain
}

Also check out Starter for jQuery , which uses a template datato bind an object to a DOM element.

+2
source

. toggle() - , , , . ( , ).

-1

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


All Articles