0

バックボーンjsで「Hello world」アプリを作成しています。私は非常に基本的なところで立ち往生しています。

var gs = { documentRoot: "" }; // アプリの名前空間を作成します

gs.Test = Backbone.Model.extend({
    url: gs.documentRoot+'/test.php',
    initialize: function(){
        this.fetch();
    }
});

gs.TestView = Backbone.View.extend({
    render: function(){
                    console.log(this.model);
        console.log(this.model.get('testId'));
    }
});

var testM = new gs.Test();

var test = new gs.TestView({model: testM});
test.render();

ここでモデルをコンソールに記録すると、サーバーからフェッチされた属性が表示されますが、test.get('attribute') からそれらの属性にアクセスできません。test.attributes をログに記録しようとしましたが、空のオブジェクトが返されますが、テストをログに記録すると、それらの属性が属性オブジェクトに表示されます。

4

3 に答える 3

1

同じ問題に悩まされている人のために、ライブラリ自体からの解決策を次に示します。

モデルの組み込み'sync'イベントを使用して、呼び出し後にモデル属性を取得しfetch()/save()ます。

testM.on('sync',function(){
   test.render();
});
于 2013-04-15T10:10:43.603 に答える
1

fetchは async メソッドなので、しばらく待つ必要があります。この場合の最善の解決策は promises です:

test.fetch().done(function() {
  console.log(test);
});

更新されたモデル:

initialize: function() {
  // save link to promise
  this.deferred = this.fetch();
}

そしてあなたのレンダリング機能:

render: function() {
  // use promise to render view after model will be fetched
  // use `bind` to save context of this view
  this.model.deferred.done(_.bind(function () {
    // model is fetched
    // all operations goes here
    console.log(this.model.get('testId')); // <- proper value
  }, this));
  console.log(this.model.get('testId')); // <- undefined
}

ここで読むことができるajaxの詳細http://api.jquery.com/jQuery.ajax

var TestModel = Backbone.Model.extend({
  url : '/test.php'
});

var test = new TestModel();

// `context` context to be passed to any callback function
test.fetch({context:test}).done(function () {
  // `this` is equals to `test` (`context` option)

  // In case if you want to get all model data:
  // the best way to get model data for read-only mode.
  // this metod return a copy of the model's attributes
  console.log(this.toJSON());
  // you can also use `this.attributes` but this is not recommended
  console.log(this.attributes());      

  // In case if you want to get some model data:
  console.log(this.get('some_attribute'));   
  // If you want to get `c` from this model ({a:{b:{c:1}}}):
  console.log(this.get('a').b.c);    
});
于 2013-04-15T06:30:44.477 に答える