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

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'));
    }
});
于 2013-04-15T06:44:33.923 回答
1

fetch是异步方法,所以你必须等待一段时间。在这种情况下,最好的解决方案是 promise:

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 回答
1

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

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

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