attr
Register custom behavior for an attribute.
can.view.attr( attributeName, attrHandler(el, attrData) ) 2.1
Parameters
-
attributeName
{String | RegExp}
A lower-case attribute name or regular expression that matches attribute names. Examples:
"my-fill"
or/my-\w/
. -
attrHandler
{function(el, attrData)}
A function that adds custom behavior to
el
.
Registers the
attrHandler
callback whenattributeName
is found in a template.Use
can.view.attr
is used to add custom behavior to elements that contain a specified html attribute. Typically it is used to mixin behavior (whereas can.view.tag is used to define behavior).The following example adds a jQueryUI tooltip to any element that has a
tooltip
attribute like<div tooltip="Click to edit">Name</div>
.Listening to attribute changes
In the previous example, the content of the tooltip was static. However, it's likely that the tooltip's value might change. For instance, the template might want to dynamically update the tooltip like:
Where
deleteTooltip
changes depending on how many users are selected:The attributes event can be used to listen to when the toolip attribute changes its value like:
To see this behavior in the following demo, hover the mouse over the "Delete" button. Then select some users and hover over the "Delete" button again:
Reading values from the scope.
It's common that attribute mixins need complex, observable data to perform rich behavior. The attribute mixin is able to read data from the element's scope. For example, toggle and fade-in-when will need the value of
showing
in:These values can be read from attrData's scope like:
But often, you want to update scope value or listen when the scope value changes. For example, the toggle mixin might want to update
showing
and the fade-in-when mixin needs to know when theshowing
changes. Both of these can be achived by using [can.view.Scope::compute compute] to get a get/set compute that is tied to the value in the scope:This value can be written to by
toggle
:Or listened to by
fade-in-when
:When you listen to something other than the attribute's element, remember to unbind the event handler when the element is removed from the page:
When to call
can.view.attr
must be called before a template is processed. When usingcan.view
to create a renderer function,can.view.attr
must be called before the template is loaded, not simply before it is rendered.