返回的backbone.js模型属性未定义,但调试显示它在控制台中设置

azt*_*chy 2 jquery symfony1 backbone.js

我现在一直在乱用骨干几天,然后出现我认为骨干最终在模型中设置属性的顺序存在误解.我有以下代码:

在model.js文件中 -

SampleModel: Backbone.Model.extend({
  urlRoot: 'a url',
  defaults: {
    attrA: 'value',
  },
  initialize: function() {
    // init of model relationships
  },
  parse: function(response) {
    this.set({attrA: response.attrAUpdateValue});
  },
});
Run Code Online (Sandbox Code Playgroud)

在view.js文件中 -

SampleView = Backbone.View.extend({
  initialize: function() {
    model = new SampleModel();
    model.fetch();

    console.log(model.get('attrA')); // Returns 'value' from default.
    console.log(model.attributes); // Inspect the attributes for the model and see that attrA does not have updated value.
  },
});
Run Code Online (Sandbox Code Playgroud)

为了使用attrA,我如何确保在更改模型之外的视图中工作时'attrA'是否有值?或者,这是在骨干领域中考虑它的方式吗?属性发生变化后,对模型执行某些操作?

在此先感谢您的帮助.

更新:我的错误我已经相应地更新了注释,之前我说第一个控制台日志将包含一个未定义的值.它应该声明该值是默认值的值,而不是应该在解析操作期间设置的预期更新值.

kul*_*esa 8

关键是,Backbone fetch是异步的.确保attrA有价值使用success回调:

SampleView = Backbone.View.extend({
  initialize: function() {
    model = new SampleModel();
    model.fetch({success: function(){
        console.log(model.get('attrA')); // Returns new value
    });
  },
});
Run Code Online (Sandbox Code Playgroud)