backbone.js set model internal attributes hash directly

前端 未结 2 2001
抹茶落季
抹茶落季 2021-02-03 11:01

Using Backbone.js I know it\'s highly recommended to set a model\'s property using the set method, and NOT by directly modifying the attributes internal hash.

However, a

2条回答
  •  猫巷女王i
    2021-02-03 11:34

    Well, if you look at the annotated source code, you'll find that set does a lot.

    What if you extended Backbone.Model with a function that does it for you:

    Backbone.Model.prototype.setByName = function(key, value, options) { 
        var setter = {}; 
        setter[key] = value; 
        this.set(setter, options); 
    };
    

    Then, you can just do what you want directly on the model:

    var model = new Backbone.Model();
    model.setByName(myProperty, "bar");
    

    That feels like a better solution to me.

    Edit

    As @earl3s pointed out, this is no longer necessary in more recent versions of Backbone. Today, you can just call model.set(myProperty, "bar") and it does what you want.

提交回复
热议问题