2010-05-05 72 views
29

如果我創建了一個JQuery小部件(下面的代碼示例),然後定義一個「public」方法,除了使用下面的表單之外,還有其他方法可以調用該方法嗎?JQuery - Widget公共方法

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

我想創建一個系列的所有定義相同的方法(基本上實現相同的接口)的小部件,並能夠調用的方法不知道任何有關該窗口小部件我目前調用方法。在當前的表單中,我需要知道我正在執行「列表」小部件上的方法。


下面是使用「public」方法創建窗口小部件的示例。

(function($) { 
    var items = []; 
    var itemFocusIdx = 0; 

    $.widget("ui.list", { 
     // Standard stuff 
     options : { ... }, 
     _create : function() { ... }, 
     destroy : function() { ... }, 

     // My Public Methods 
     publicMethod : function() { ... } 
     ... 
    }); 
}(jQuery)); 
+0

他們是否必須使用$ .widget,還是打開使用繼承和$ .fn? – balupton 2010-07-19 02:06:49

回答

22

的jQuery UI部件使用jQuery的$ .data(...)方法間接將窗口小部件類與DOM元素相關聯。首選方法來調用小部件的方法正是由馬克斯描述...

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

...但如果你想現場返回值,你將有更好的運氣,稱這是這樣經由數據的方法:

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

然而,使用第二種方式側步驟的整個jQuery的UI部件的圖案,並且如果可能的話可能應該避免。

-2

這個怎麼樣:

$("#list").list.publicMethod 

當你正在ui.list與鍵擴展:值對集合

+0

似乎沒有工作 – thomaux 2012-02-27 09:36:02

0

試試這個:

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

這正是OP試圖不這樣做...... – thomaux 2012-02-24 10:29:53

2

稍微偏離主題,我知道,但你可能想看看jquery Entwine

這提供了一種繼承和多態的形式,允許一些聰明的行爲與簡單的代碼。這聽起來像這會做你正在做的事情。

1

可以說你有listlist2,並superList ......讓我們稱之爲「publicMethod」對他們每個人:

$.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"); 
0

該解決方案通過@ Jiaaro的解決方案的啓發,但我需要一個返回值並作爲JavaScript函數實現,而不是擴展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](); 
      } 
     } 
    }