Dealing with non-saveable values in Backbone

后端 未结 3 428
情书的邮戳
情书的邮戳 2021-01-18 07:23

Is there a standard way to deal with non-saveable values in Backbone.

e.g.

MyModel = Backbone.extend(Backbone.Model, {
    initialize: function () {         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-18 08:12

    I think this should do it. Define your Model defaults as your valid schema and then return only the subset of this.attributes that is valid during toJSON.

    var Model = Backbone.Model.extend({
      defaults: {
        foo: 42,
        bar: "bar"
      },
    
      toJSON: function () {
        var schemaKeys = _.keys(this.defaults);
        var allowedAttributes = {};
        _.each(this.attributes, function (value, key) {
        if (_.include(schemaKeys, key)) {
          allowedAttributes[key] = value;
        }
        return allowedAttributes;
      }
    });
    

    Note that _.pick would make the code a bit shorter once you have underscore 1.3.3 available. I haven't seen a "tried and tested" convention in my travels through the backbone community, and since backbone leaves so many options open, sometimes conventions don't emerge, but we'll see what this stackoverflow question yields.

提交回复
热议问题