JQuery - Widget Public Methods

前端 未结 6 1264
野性不改
野性不改 2020-12-24 11:59

If I create a JQuery widget (code example below), and then define a \"public\" method, is there any other way to call the method other than using the following form?

6条回答
  •  盖世英雄少女心
    2020-12-24 12:49

    lets say you have list, list2, and superList... let's call "publicMethod" on for each of them:

    $.fn.callWidgetMethod = function(method) {
      var $this = this,
          args = Array.prototype.slice.call(arguments, 1);
    
      // loop though the data and check each piece of data to
      // see if it has the method
      $.each(this.data(), function(key, val) {
        if ($.isFunction(val[method])) {
          $this[key].apply($this, args);
    
          // break out of the loop
          return false;
        }
      });
    }
    
    $("#some-element").list();
    $("#another-element").list2();
    $("#hydrogen").superList();
    
    $("#some-element").callWidgetMethod("publicMethod");
    $("#another-element").callWidgetMethod("publicMethod");
    $("#hydrogen").callWidgetMethod("publicMethod");
    

提交回复
热议问题