2010-11-18 13 views
2

javascriptのスコープに問題があります。 jqueryプラグインを使用して、ドロップダウンコントロールのラッパーであるクラスを作成しています。JavaScriptスコープの問題

問題がloadJsonList関数にある場合、メソッドが存在しないため、this.addOption(s.itemValue, s.itemText);の呼び出しは機能しません。私はJSが奇妙なスコープを持っていることを知っていますが、私はそのスコープでその関数をどのように実行できるのか分かりませんでしたか?

jQuery.Class.extend("DDL", 
{ 
    id: '', 
    isTelerik: false 
}, 
{ 
    init: function (newid) { 
     this.Class.id = newid; 

    }, 
    getValue: function() { 
     return $('#' + this.Class.id).val(); 
    }, 
    getText: function() { 
     return $('#' + this.Class.id + ' :selected').text(); 
    }, 
    setValue: function (newValue) { 
     try { 
      $('#' + this.Class.id).val(newValue); 
     } catch (err) { 
      alert(err); 
     } 
    }, 
    setText: function (newText) { 
     try { 
      $('#' + this.Class.id + ' :selected').text(newText); 
     } catch (err) { 
      alert(err); 
     } 
    }, 
    loadJsonList: function (list, param1, param2, param3) { 
     this.clearItems(); 

     //init the service 
     var j = new JsonRPC(); 

     // get the cut down data table 
     var dt = j.getDropDownData(list, param1, param2, param3); 

     // parse the datatable and load it into the telerik combo box 
     jQuery.each(dt, function (i, s) { 
      this.addOption(s.itemValue, s.itemText); 
     }); 
    }, 
    addOption: function (value, text) { 
     $('#' + this.Class.id).append('<option value="' + value + '">' + text + '</option>'); 
    }, 
    removeOption: function (value) { 
     $('#' + this.Class.id + ' option[value="' + value + '"]').remove(); 
    }, 
    clearItems: function() { 
     $('#' + this.Class.id + ' option').remove(); 
    } 
}); 
+1

は、少し知識をひけらかすことにします。 – slebetman

答えて

3

シンプルなもの。あなたには、いくつかの他の名前の下にthis変数への参照を保存するので、JavaScriptは、機能レベルのスコープを使用しています。その関数のスコープで

loadJsonList: function (list, param1, param2, param3) { 
     // save a reference for use in the each function later 
     var self = this; 
     this.clearItems(); 

     //init the service 
     var j = new JsonRPC(); 

     // get the cut down data table 
     var dt = j.getDropDownData(list, param1, param2, param3); 

     // parse the datatable and load it into the telerik combo box 
     jQuery.each(dt, function (i, s) { 
      // use self instead of this! 
      self.addOption(s.itemValue, s.itemText); 
     }); 
    }, 
2

thisあなたのオブジェクトの同じthisに等しくない場合、あなたはエイリアス変数を割り当てる必要があります内部関数の内部にアクセスするために、周囲のスコープでそれに:あなたが探しているものを

var self = this;  
jQuery.each(dt, function (i, s) { 
    self.addOption(s.itemValue, s.itemText); 
}); 
0

はjQueryのプロキシメソッド(http://api.jquery.com/jQuery.proxy)です:

次のよう

だからあなたの上記の例では、あなたはそれを使用したい:あなたはスコープが、結合について話していないthis` `について話すとき

loadJsonList: function (list, param1, param2, param3) { 

    // ... 

    jQuery.each(dt, jQuery.proxy(function (i, s) { 
     this.addOption(s.itemValue, s.itemText); 
    }, this)); 
},