Backbone.js - custom setters

前端 未结 3 889
说谎
说谎 2021-02-19 08:44

Imagine a simple backbone model like

window.model= Backbone.Model.extend({
   defaults:{
      name: \"\",
      date: new Date().valueOf()
   }
})
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-19 09:12

    UPDATE: you can use the plug-in: https://github.com/berzniz/backbone.getters.setters


    You can override the set method like this (add it to your models):

    set: function(key, value, options) {
        // Normalize the key-value into an object
        if (_.isObject(key) || key == null) {
            attrs = key;
            options = value;
        } else {
            attrs = {};
            attrs[key] = value;
        }
    
        // Go over all the set attributes and make your changes
        for (attr in attrs) {
            if (attr == 'name') {
                attrs['name'] = attrs['name'].toLowerCase();
            }
        }
    
        return Backbone.Model.prototype.set.call(this, attrs, options);
    }
    

提交回复
热议问题