— Polymer — 1 min read
A data binding connects data from a custom element (the host element) to a property or attribute of an element in its local DOM (the child or target element). The host element data can be a property or sub-property represented by a data path, or data generated based on one or more paths.
数据绑定能够将host元素和target元素的property或者attribute相互链接床单。这里数据指的是路径(Paths)
数据绑定有两种绑定方式:
=
绑定property,$=
绑定attribute(href,style,...)[[ ]]
或者\{\{ \}\}
"my name is {{ name }}"
将target元素的name属性绑定到当前元素的my-Name属性。 注意驼峰式和dash式命名的转换规则(property name to attribute name mapping)
相当于绑定到target元素的textContent
属性上
Binding to text content is always one-way, host-to-target.
注意,文字节点的绑定永远都是单向的(host to target)
attribute绑定相当于
property绑定相当于
因此,一些attribute同样可以使用property形式绑定:
需要注意的是: attribute形式的数据绑定只能是单向的([[ ]]
)
There are a handful of common native element properties that Polymer can't data-bind to directly, because the binding causes issues on one or more browsers.
一些原生的property无法使用=
绑定数据,需要使用attribute形式的$=
才能成功绑定。
Attribute | Property | Notes |
---|---|---|
class | classList , className | Maps to two properties with different formats. |
style | style | By specification, style is considered a read-only reference to a CSSStyleDeclaration object. |
href | href | |
for | htmlFor | |
data-* | dataset | Custom data attributes (attribute names starting with data- ) are stored on the dataset property. |
value | value | Only for <input type="number"> . |
data binding to the
value
property doesn't work on IE for numeric input types. For this specific case, you can use one-way attribute binding to set thevalue
of a numeric input. Or use another element such asiron-input
orpaper-input
that handles two-way binding correctly.
可以在data-binding表达式前面添加!
号取反
注意:
!
不能!!
computed binding类似于computed property。
An element can have multiple computed bindings in its template that refer to the same computing function. 一个元素里面可以有多个使用同样的computing function的computed binding
computed binding并不完全等同于computed property,差异有下面几点:
Commas in literal strings: Any comma occurring in a string literal must be escaped using a backslash (
\
).
如果参数是字符串,那么字符串里面所有的逗号都要被转义
Computed bindings are one-way. A computed binding is always one-way, host-to-target.
computed binding只能在单向绑定中使用
可以在字符串里面或者textContent里面使用绑定标记
注意:
\{\{ \}\}
记号。To keep annotation parsing simple, Polymer doesn't provide a way to bind directly to an array item.
为了解析简单,Polymer无法直接绑定一个数组里面的元素
有下面几种方法可以解决:
dom-repeat
里面已经为每个数组里面的元素创建了一个子scope,因此可以直接bindingarray-selector
同上,可以直接绑定一个元素或者被选择的元素集合为了达到非Polymer元素上面的双向绑定,可以使用下面的标记:
基于约定大于配置的原理,如果target-prop
的变化通知函数是target-prop-changed
则该定义可以省略。