试图了解 backbone 模型的初始化和 collections

Trying to understand backbone initialization of models and collections

我有一个 collection 模型,其中一个字段可能为空。在那种情况下,我想在列表视图中显示 "none"。但是,如果该字段不为空,我想显示它的内容。这是我的代码。

我的模特:

App.Models.EventType = App.Helpers.Model.extend(
  {
    initialize: function(){
      console.log('model init');
      this.set('etcName', this.get('etcName') === null ? 'none':this.get('etcName'));
    },
    url       : function(){
      if(_.isUndefined(this.id)){
        return '/api/event_types_controller/event_type';
      }
       return '/api/event_types_controller/event_type/' + this.id;
    }
  });

我的Collection:

App.Collections.EventTypes = App.Helpers.Collection.extend(
  {
    initialize: function(){
      console.log('collection init');
    },
    url      : '/api/event_types_controller/get_event_types',
    model    : App.Models.EventType,
    sortOrder: 'asc',
    sortBy   : 'eventTypeName'
  }
);

这适用于列表视图。我在控制台中看到数据是从服务器检索的,然后模型为检索到的每条记录初始化代码 运行s。这是返回的 JSON 的示例:

{"eventTypeID":35,"eventTypeName":"DEPO","description":"","instructions":"","lawyersOnly":0,"eventTypeCategoryID":3,"lockedType":1,"etcName":"Deposition"},
{"eventTypeID":34,"eventTypeName":"DENY","description":"Denial","instructions":"","lawyersOnly":0,"eventTypeCategoryID":0,"lockedType":0,"etcName":null}

但是,现在我需要加载单个记录。我知道我可以在获取中放入一个 success: function() 但看起来正确的功能是一致的 before/after 数据已加载初始化。没有?

来自我的路由器:

eventTypesSettingsEdit: function(id){
  var eventTypeEditModel = new App.Models.EventType({id: id});
  var eventTypeContent = new App.Views.Settings.EditEventType({model: eventTypeEditModel});
  App.Helpers.htmlView(eventTypeContent, '#content');
  eventTypeEditModel.fetch();
},

在这种情况下,模型的初始化代码在加载数据之前执行。这对我来说似乎不一致。坦率地说,我希望初始化代码 运行 在包括数据获取在内的任何事情之前,并且应该有某种 post 获取初始化,可以在其中操作数据。

任何人都可以指出如何正确处理需要为列表和编辑视图修改传入数据的情况吗?

您应该在模型上使用#parse。仅在从服务器获取时调用。

http://backbonejs.org/#Model-parse