Any recommendations for deep data structures with Backbone?

后端 未结 3 813
野趣味
野趣味 2021-01-30 23:46

I\'ve run into a headache with Backbone. I have a collection of specified records, which have subrecords, for example: surgeons have scheduled procedures, procedures have equip

3条回答
  •  孤独总比滥情好
    2021-01-31 00:13

    So, one way I solved this problem is by doing the following:

    1. Have all models inherit from a custom BaseModel and put the following function in BaseModel:

          convertToModel: function(dataType, modelType) {
              if (this.get(dataType)) {
                  var map = { };
                  map[dataType] = new modelType(this.get(dataType));
                  this.set(map);
              }
          }
      
    2. Override Backbone.sync and at first let the Model serialize as it normally would:

      model.set(response, { silent: true });

    3. Then check to see if the model has an onUpdate function:

                  if (model.onUpdate) {
                      model.onUpdate();
                  }
      
    4. Then, whenever you have a model that you want to generate submodels and subcollections, implement onUpdate in the model with something like this:

              onUpdate: function() {
                  this.convertToModel('nameOfAttribute1', SomeCustomModel1);
                  this.convertToModel('nameOfAttribute2', SomeCustomModel2);
              }
      

提交回复
热议问题