0

'this'キーワードに問題があります。以下が機能しない理由は理解できますが、修正方法がわかりません...

//Namespace
var CPT = CPT || {};

//Constructor
CPT.Grid = function (hostElement, surlWeb) {
  this.hostElement = hostElement;
  this.surlWeb = surlWeb;
}

//Prototype
CPT.Grid.prototype = {

  init: function () {

    $.ajax({
      url: this.surlWeb,
      headers: { "accept": "application/json" },
      success: this.showItems
    });
  },

  showItems: function (data) {
    //do some work 

    // this is the error... no access to hostElement because 'this' is the AJAX call
    this.hostElement.html(items.join(''));
  }
}

function getProducts() {
  var grid = new CPT.Grid($("#displayDiv"), someUrl);
  grid.init();
}

別のshowItems関数を使用しないことでこれを修正できる可能性が高いことはわかっていますが、別の方法で修正する方法を確認したいと思います。理想的には、現在のオブジェクトへの参照をサクセスハンドラーに渡したいのですが、その方法がわかりません...

4

2 に答える 2

5

そのためのcontextオプション$.ajaxは次のとおりです。

$.ajax({
  // ...
  context: this,
  success: this.showItems
});

これにより、現在の(正しい)thisがに渡されるようになりshowItemsます。

于 2012-10-20T17:05:05.167 に答える
1

関数参照を渡しています。同じコンテキストはありません。

..。

var self = this;
$.ajax({
      url: this.surlWeb,
      headers: { "accept": "application/json" },
      success: function(){self.showItems.apply(self, arguments)
    });
  },

または

コンテキストをメソッドにバインドできます

this.showItems = this.showItems.bind(this); // will not work IE < 9
 $.ajax({
          url: this.surlWeb,
          headers: { "accept": "application/json" },
          success: this.showItems
        });
      },
于 2012-10-20T17:04:33.773 に答える