convert
can.Map.attributes.static.convert
You often want to convert from what the observe sends you to a form more useful to JavaScript.
For example, contacts might be returned from the server with dates that look like: "1982-10-20".
We can observe to convert it to something closer to new Date(1982,10,20)
.
Convert comes with the following types:
The following sets the birthday attribute to "date" and provides a date conversion function:
If a property is set with an object as a value, the corresponding converter is called with the unmerged data (the raw object) as the first argument, and the old value (a can.Map) as the second:
Differences From
attr
The way that return values from convertors affect the value of an Observe's property is different from attr's normal behavior. Specifically, when the property's current value is an Observe or List, and an Observe or List is returned from a convertor, the effect will not be to merge the values into the current value as if the return value was fed straight into
attr
, but to replace the value with the new Observe or List completely. Because of this, any bindings you have on the previous observable object will break.If you would rather have the new Observe or List merged into the current value, call
attr
directly on the property instead of on the Observe:Assocations and Convert
If you have assocations defined within your model(s), you can use convert to automatically call serialize on those models.