1

AJAXを介してHTMLドキュメントを取得するJavascriptアプリを作成し、それを処理して、イベントリスナー(具体的には、ブートストラップポップオーバー)をその中の要素にアタッチする必要があります。リスナーを接続するのに問題があり、スコープの問題だと思います。関連するコードは次のとおりです。

var App = function(site){

  this.load = function(data, func){
    $('div.ajax').html(data);
    func();
  }

  this.dispatch = function(data){

    if(data.indexOf('from_server') !== -1){
      this.load(data, this.process);
      console.log('Loaded view from Matisse.');
      return true;
    }

  }

  this.process = function(){
    this.popovers('from_server');
  }

  this.popovers = function(el){
    var that = this;
    $('img.artwork.gallery', el).each(function(){
       $(this).popover({ trigger: 'hover', content: that.popoverPopulate(this) });
    });
  }

  this.popoverPopulate = function(el){
    return $(el).next('div.popover_content').html();
  }
}

var APP = new App();

$.ajax({blah: blah, success: function(data){ APP.dispatch(data); }});

...

問題は(私が思うに)のfunc()呼び出しですthis.load。これを渡すとthis.process()、「this」のスコープがウィンドウになり、エラーが発生します。合格this.processすると、作成されたのはラムダですが、それでも失敗します。私が呼ぶthis.func()と同じ問題が発生します。

a)コールバックを使用してAppオブジェクト内にスコープを保持する、またはb)ロード後にハンドラーを呼び出すようにこの混乱を再編成するにはどうすればよいですか?

4

3 に答える 3

5

var that=thisすべてのメソッドでスコープトリックを使用したいと思います。

var App = function(site){

  var that = this;

  this.load = function(data, func){
    $('div.ajax').html(data);
    func();
  }

  this.dispatch = function(data){

    if(data.indexOf('from_server') !== -1){
      that.load(data, that.process);
      console.log('Loaded view from Matisse.');
      return true;
    }

  }

  this.process = function(){
    that.popovers('from_server');
  }

  this.popovers = function(el){
    $('img.artwork.gallery', el).each(function(){
       $(that).popover({ trigger: 'hover', content: that.popoverPopulate(this) });
    });
  }

  this.popoverPopulate = function(el){
    return $(el).next('div.popover_content').html();
  }
}
于 2012-04-11T02:04:16.343 に答える
4

このようなもの:

var App = function(site){
    var self = this; //-<!!!

    this.load = function(data, func){

    ...

    this.dispatch = function(data){
        if(data.indexOf('from_server') !== -1){
            self.load(data, self.process);
    ...
于 2012-04-11T02:06:11.583 に答える
1

これは、現在使用されているコンテキストを指します。したがって、これを行うthis.processと、ウィンドウがターゲットになります。そうすると、オブジェクトApp.load(data, App.process)内のプロセス関数がターゲットになります。App

于 2012-04-11T02:06:02.783 に答える