setter
can/map/setterDeprecated 2.1
The setter plugin (and the attributes plugin) have been deprecated in favor of the new define plugin, which provides the same functionality. It will still be maintained up to 3.0 and potentially after. Projects using setters should consider switching to define setters.
Specify setter methods on can.Maps.
setATTR: function(newValue,setValue,setErrors)
Specifies a setter method for the ATTR
attribute.
Parameters
-
ATTR
{String}
The capitalized attribute name this setter will set.
-
newValue
{*}
The propsed value of the attribute specified by attr.
-
setValue
{setValue(value)}
A callback function that can specify
undefined
values or the value at a later time. -
setErrors
{setErrors(errors)}
A callback function that can specify error data if the proposed value is in error.
Returns
{*}
If a non-undefined value is returned, that value is set as the attribute's value. If
undefined is returned, it's assumed that the setValue
callback will be called. Use setValue
to
set undefined values.
Use
can.Map.setter(name, setValue(value), setErrors(errors))
extends the Map object to provide convenient helper methods for setting attributes on a map.The attr function looks for a camel-case
setATTR
function to handle setting theATTR
property. For example, the following makes sure thebirthday
attribute is always a Date type.By providing a function that takes the raw data and returns a form useful for JavaScript, we can make our maps automatically convert data.
If the returned value is
undefined
, this means the setter is either in an async event or the attribute(s) were not set.Differences From
attr
The way that return values from setters affect the value of an Map's property is different from attr's normal behavior. Specifically, when the property's current value is an Map or List, and an Map or List is returned from a setter, 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 Map or List completely:If you would rather have the new Map or List merged into the current value, call
attr
inside the setter:Error Handling
Setters can trigger errors if values passed didn't meet your defined validation(s).
Below is an example of a School observable that accepts a name property and errors when no value or a empty string is passed.
Demo
The example app is a pagination widget that updates the offsets when the Prev or Next button is clicked.
Notice the
setCount
andsetOffset
setters.