无法访问属性模型主干js

时间:2013-04-15 06:23:13

标签: backbone.js

我正在骨干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,它给出了空对象,但是当我记录测试时,它会在属性对象中显示这些属性。

3 个答案:

答案 0 :(得分:2)

model#fetch方法有一个successerror回调选项,可以传递给fetch。当来自服务器的响应到来时,将调用成功回调。

测试模型的获取属性的正确方法是

test.fetch({
    success: function(model){
        // model here and test are same
        console.log(model);
        console.log(test.toJSON());
        // access your attribute with name `attributeName`
        console.log(test.get('attributeName'));
    }
});

答案 1 :(得分:1)

fetch是异步方法,因此您必须等待一段时间。 在这种情况下,最好的解决方案是承诺:

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);    
});

答案 2 :(得分:1)

对于那些遇到同样问题的人来说,这是图书馆本身的解决方案。

使用模型的内置'sync'事件在fetch()/save()调用后获取模型属性。

testM.on('sync',function(){
   test.render();
});