Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - custom setters

Imagine a simple backbone model like

window.model= Backbone.Model.extend({
   defaults:{
      name: "",
      date: new Date().valueOf()
   }
})

I'm trying to find a way to always make the model store the name in lower-case irrespective of input provided. i.e.,

model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior

What's the best way of doing this? Here's all I could think of:

  1. Override the "set" method
  2. Use a "SantizedModel" which listens for changes on this base model and stores the sanitized inputs. All view code would then be passed this sanitized model instead.

The specific "to lower case" example I mentioned may technically be better handled by the view while retrieving it, but imagine a different case where, say, user enters values in Pounds and I only want to store values in $s in my database. There may also be different views for the same model and I don't want to have to do a "toLowerCase" everywhere its being used.

Thoughts?

like image 321
Naren Avatar asked Oct 20 '11 21:10

Naren


1 Answers

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);
}
like image 177
Tal Bereznitskey Avatar answered Sep 28 '22 06:09

Tal Bereznitskey