Backbone.js - custom setters

前端 未结 3 886
说谎
说谎 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:38

    It would be a hack, because this isn't what it was made for, but you could always use a validator for this:

    window.model= Backbone.Model.extend({
       validate: function(attrs) {
          if(attrs.name) {
             attrs.name = attrs.name.toLowerCase()
          }
    
          return true;
       }
    })
    

    The validate function will get called (as long as the silent option isn't set) before the value is set in the model, so it gives you a chance to mutate the data before it gets really set.

提交回复
热议问题