2009-04-15 64 views

回答

3

使用this._on() method綁定處理程序。此方法由jQuery UI小部件工廠提供,並將確保處理函數內的this始終引用小部件實例。

_create: function() { 
    ... 
    this._on(this.selectElement, { 
     change: "_onChange" // Note: function name must be passed as a string! 
    }); 
}, 
_onChange: function (event) { 
    // 'this' is now the widget instance. 
}, 
+0

由於原始答案(來自我自己)已被替代,因此更改了此答案。 – 2013-07-22 17:05:36

-1
(function($){ 
    $.widget(
     "ui.my_ui_widget", 
     { 
      //------------------------------------------------------------------ 
      _init : function(){ 
       var o = this.options; // 2 
       o.context = this; 
       ... 
       // 3 
       $('#'+o.id).bind('change', {context:this}, this.on_change); 
       ... 
      }, 
      //------------------------------------------------------------------ 
      on_change: function(event) { 
       var context = event.data.context; // 4 
      var o  = context.options; 

       o.id = ''; // 5 

       var sel = this; // event handler context 
       var selectedIndex = sel.selectedIndex; 
       if (selectedIndex < 0) return; 

       o.id = sel.options[selectedIndex].value; // 5 

       context.update_ui(); // 6 
      }, 
      //------------------------------------------------------------------ 
     } 
    ); 
    //-------------------------------------------------------------------------- 
    $.extend($.ui.my_ui_widget, { 
     getter  : "id", 
     getterSetter : "xxx, yyy", 

     defaults : { 
       ... 
      context : undefined, // 1 
      ... 
      on_change : undefined, 
       ... 
      } 
     } 
    ); 
    //-------------------------------------------------------------------------- 
})(jQuery); 

$(document).ready(function() { 
    $('.my_ui_widget').each(function(i) { 
      var id = this.id; 
      var mode = ''; 

      try{ 
       mode = this.attributes['mode'].value; 
      } catch(err) { 
       mode = 'unlinked'; 
      } 

      $('#'+id).my_ui_widget({id:id, mode:mode}); 
     } 
    ); 
}); 
  1. 從一開始就
  2. 啓用上下文記住Widget的這個作爲背景(或自如果願意的話)需要的時候
  3. 傳遞上下文jQuery的方式給事件處理程序
  4. 提取物根據需要處理側
  5. 訪問控件數據
  6. 調用插件的方法
+0

ev.data is undefined,for: var context = ev.data.context; jQuery(ev.target).data(「autocomplete」)未定義,如下所示: jQuery(ev.target).data(「autocomplete」)。options; // 4 – 2011-11-09 21:33:05

1

您也可以在事件處理程序中簡單地執行此操作(例如,對於自動填充小部件)

select: function(event, ui) { 
    var options = jQuery(event.target).data("autocomplete").options; 

    ... 
} 
+1

jQuery – 2011-11-09 21:13:55

相關問題