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:
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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With