2

thisbackbone.js プロジェクトで問題が発生しています。

これは私の見解です:

app.SomeView = Backbone.View.extend({
  render: function() {
    var that = this;
    $.getJSON(someURL, function(result) {
      that.property = result.something;
    });

    return this;
  }
})

不可解なことに、内部でgetJSONコールバックthat.propertyが設定されますが、その関数が終了するとすぐに、つまり at return this- that.propertyequalsundefinedと同じようにthis.property.

私は何を間違っていますか?

4

2 に答える 2

4

私のコメントで述べたように、$.getJSON非同期です。が適切な URL を取得しているrender間も関数は実行を続けるため、最終的には$.getJSONreturn this;that.property = result.something

于 2012-08-16T16:16:13.423 に答える
4

モデルを使用していない理由がわかりません。あなたの質問に答えると、さまざまな解決策があります。最初の解決策は次のとおりです。

イベントの使用:

app.SomeView = Backbone.View.extend({
  render: function() {
    var that = this;
    $.getJSON(someURL, function(result) {
      that.property = result.something;
      that.trigger('DataLoaded', that);
    });

    return this;
  }
});
var view = new app.SomeView();
view.on('DataLoaded', function(theView){ 
  console.log( theView );
});

2 つ目は、コールバックを追加して渡す必要があります。

app.SomeView = Backbone.View.extend({

  render: function(callback) {
    var that = this;
    $.getJSON(someURL, function(result) {
      that.property = result.something;
      callback(that);
    });
    return this;
  }
});
var view = new app.SomeView();
view.render( function(theView){ 
  console.log( theView );
});

私の回答は、あなたが作成した質問を修正するために書かれました。しかし、長期的な改善のために、Models には基本的にサーバーから JSON をロードしてそれを Model に関連付ける fetch メソッドがあることをご存知ですか? http://backbonejs.org/#Model-fetch JSON を読み込む方法は次のとおりです。

app.SomeModel = Backbone.Model.extend({
  urlRoot : someURL
});
app.SomeView = Backbone.View.extend({
  initialize : function(){
     this.model.on('change', this.render);
  },
  render: function() {
    console.log( this.model.toJSON() );
    return this;
  }
});
var view = new app.SomeView(new app.SomeModel());
view.model.fetch();
于 2012-08-16T18:01:00.080 に答える