Backbone fetch模型然后呈现视图

时间:2016-04-30 22:50:49

标签: javascript backbone.js

在模型上执行获取操作时,我可以看到API以JSON格式返回所需的数据。记录模型的控制台在“已更改”对象中显示新数据。

获取之前和之后:

Object {
  cid: "c1",
  attributes: Object,
  _changing: false,
  _previousAttributes: Object,
  changed: Object,
  id: undefined,
  _pending: false
}

Object {
  cid: "c1",
  attributes: Object,
  _changing: false,
  _previousAttributes: Object,
  changed: Object[1],
  id: undefined,
  _pending: false
}

显然正在获取数据,并且它存在于模型中。但是,在渲染时,会显示默认值。

App.Models.Document = Backbone.Model.extend({

  defaults: {
     id: '',
     owner: 0,
     created: '',
     lastupdate: '',
     content: 'Default document content'
  },

  url: '/api/'

});


App.Views.DocumentView = Backbone.View.extend({

  tagName: 'textarea',
  className: 'editor',

  template: App.Template('editortemplate'),

  initialize: function() {

  // As proposed in so many similar questions
  this.listenTo(this.model, "change", this.render);

  },
  render: function() {

    this.$el.html( this.template( this.model.toJSON() ) );

    $(".app-content").html(this.$el);

    return this;

  }
});


a = new App.Models.Document();
a.fetch();
b = new App.Views.DocumentView({ model: a });
b.render();

如何使用新数据正确更新视图?

如果我从模型中删除默认值,则不会定义“内容”。

2 个答案:

答案 0 :(得分:2)

您可以在模型上收听Backbone sync事件。成功调用服务器后,sync将触发

this.listenTo(this.model, 'sync', this.render);

您也可以在初始化方法中将模型提取移动到App.Views.DocumentView。 成功时,您将呈现视图:

App.Models.Document = Backbone.Model.extend({
  defaults: {
    id: '',
    owner: 0,
    created: '',
    lastupdate: '',
    content: 'Default document content'
  },

  url: '/api/'
});


App.Views.DocumentView = Backbone.View.extend({
  tagName: 'textarea',
  className: 'editor',
  template: App.Template('editortemplate'),
  initialize: function() {
    var self = this;

    // model fetch
    this.model.fetch({
      success: function() {
        // call render
        self.render();
      },
      error: function () {
        // handle error
      }
    });

    // As proposed in so many similar questions
    this.listenTo(this.model, "change", this.render);
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    $(".app-content").html(this.$el);
    return this;
  }
});


var myModel = new App.Models.Document();
var myView = new App.Views.DocumentView({
  model: myModel
});
myView.render();

答案 1 :(得分:2)

Backbone.Model期望从服务器返回一个对象,而不是一个数组。如果是集合,则应返回数组。

因此,在您的情况下,您需要定义一个parse方法来返回包含数据的对象:

App.Models.Document = Backbone.Model.extend({
  defaults: {
    owner: 0,
    created: '',
    lastupdate: '',
    content: 'Default document content'
  },
  url: '/api/',
  parse: function(response) {
    return response[0];
  }

});