JQuery - Widget Public Methods

落花浮王杯 提交于 2019-11-29 23:54:17

jQuery UI widgets use jQuery's $.data(...) method to indirectly associate the widget class with the DOM element. The preferred way to call a method on the widget is exactly what was described by Max...

$('#list').list('publicMethod');

...but if you want to field a return value, you'll have better luck calling it this way, via the data method:

$('#list').data('list').publicMethod();

However, using the second way side-steps the whole jQuery UI widget pattern, and should probably be avoided if possible.

Slightly off-topic, I know, but you may want to look at jquery Entwine.

This provides a form of inheritance and polymorphism which allows some clever behaviour with simple code. It sounds like this would do what you are trying to do.

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

This solution is inspired by @Jiaaro's solution, but I needed a return value and implemented as a JavaScript function rather than extending jQuery:

var invokeWidgetMethod = function(methodName, widgetElem)
    {
        var $widgetElem = $(widgetElem),
            widgetData = $widgetElem.data(),
            dataName,
            dataObject;

        for(dataName in widgetData)
        {
            dataObject = widgetData[dataName];
            if ($.isFunction(dataObject[methodName])) {
                return dataObject[methodName]();
            }
        }
    }
Max Kramnik

Try this:

$("#list").list("publicMethod");

How about this one:

$("#list").list.publicMethod

As you are extending ui.list with your key:value pair set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!