Skip to content

2017

Polymer 2.0 文档笔记(2) ShadowDOM

ShadowDOM API

var div = document.createElement('div'); 
var shadowRoot = div.attachShadow({mode: 'open'}); 
shadowRoot.innerHTML = '<h1>Hello Shadow DOM</h1>';

ShadowDOM Composition

主要概念:

  • LightDOM: 元素的实际子孙节点,浏览器不会对LightDOM做任何的修改和移动。但是渲染的时候会渲染到相对于的slot节点之下,如果找不到对应的slot节点,则不会渲染。
  • ShadowDOM: 不解释。。。
  • Slot: slot标签是LightDOM插入到ShadowDOM中的标记。可以设置name属性来匹配对应的LightDOM。Slot标签不会渲染,但是还是会存在(即能够参与事件传递)。另外如果一个LightDOM找不到匹配的slot插入点,则改LightDOM也不会被渲染。
  • Flatterned Tree: LightDOM通过ShadowDOM里面的slot标记合并在一起(flattern)的抽象的DOM树(devTools中不可见),是最后浏览器实际用来渲染的DOM树。

需要注意的是:

Slots can only be selected explicitly, by slot name. It's impossible to select content implicitly, based on a tag name or an arbitrary selector like :not(.header).

slot只能用slot name来区分、选中。不能用其他任意的css选择器。

各个slot之间的区域是互斥的,而且 只能选择top-level元素 (包括后面的::slotted(selector)选择器)。

<!-- shadow DOM v1 template -->
<template>
  <!-- this slot gets any top-level nodes that don't have slot
       attributes. -->
  <slot></slot>
  <!-- the following insertion point gets any top-level nodes that have
       slot="special". -->
  <slot name="special"></slot>
  <!-- top-level nodes that have slot attributes with other values
       don't get distributed at all. -->
</template>

Fallback content

实际上就是可以在模版的slot里面写东西,作为一个默认值

Mulit-level distribution

多级slot嵌套。flatterning的时候规则是从外向里, 因此父节点的slot下面的lightDOM会渲染在子节点的LightDOM之下。

Slot APIs && Observe added and removed children

  • HTMLElement.assignedSlot
  • HTMLSlotElement.assignedNodes
  • HTMLSlotElement.slotchange(event)
  • Polymer.FlattenedNodesObserver
  • Polymer.FlattenedNodesObserver.getFlattenedNodes(node)
  • new Polymer.FlattenedNodesObserver(this.$.slot,(info)=>{})

详情参考https://www.polymer-project.org/2.0/docs/devguide/shadow-dom

Shadow DOM polyfills

因为shadowDOM不是每个浏览器都支持,所以使用了webcomponents.js中的shadyDOM和shadyCSS两个polyfills。

How the polyfills work

The polyfills use a combination of techniques to emulate shadow DOM: Shady DOM: Maintains the logical divisions of shadow tree and descendant tree internally, so children added to the light DOM or shadow DOM render correctly. Patches DOM APIs on affected elements in order to emulate the native shadow DOM APIs. Shady CSS: Provides style encapsulation by adding classes to shadow DOM children and rewriting style rules so that they apply to the correct scope.

ShadyDOM

ShadyDOM主要原理是patch原生DOM API来提供跟native shadowDOM一致的接口。在内存中维护了一个保存LightDOM的children树和一个保存ShadowDOM的ShadowRoot树。但是实际上元素下面就是一颗渲染好的flatterned树。因为这个是就是实际上的用来渲染的树,所以不存在slot,因此shadyDOM polyfills方案里面的slot元素不参与事件传递。

ShadyCSS

ShadyCSS主要提供了原生ShadowDOM规则的支持和两个cssnext特性:CSS custom propertiescustom property mixins. Scoped CSS特性的实现原理跟Vue相似:对元素的ShadowDOM添加class,并重写CSS的匹配规则。

ShadowDOM styling

ShadowDOM样式三大原则:

  1. 外层的样式不会对内层样式进行匹配。
  2. 内层样式不会影响外层样式。
  3. 可继承的css属性(例如:color)等,内层可以照样继承自外层。

两个特殊伪类: - 选择ShadowDOM的根节点节点:host/:host(selector)

#shadow-root
  <style>
    /* custom elements default to display: inline */
    :host {
      display: block;
    }
    /* set a special background when the host element
       has the .warning class */
    :host(.warning) {
      background-color: red;
    }
  </style>

  • 选择分布式节点——::slotted()
  • slotted()选择器右边不能写任何其他选择器。
  • slotted(selector) 里面的selector只能是简单选择器,并且只能选择顶级元素。
  • slotted(*) 选择默认的LightDOM(不包含有name值的slot)
  • slotted(slot=tkw) 选择name为tkw的LightDOM
<dom-module>
<template>
  <style>
    ::slotted(img){ 
      border-radius: 103%;
    }
  </style>
  <div><slot></slot></div>
</template>
<script>
  // define the element's class element
  class XFoo extends Polymer.Element {
    // 'is' getter, return the tag name which is lowercased. required.
    static get is(){
      return 'x-foo';
    }
    // Define the properties.
    static get properties() {}
    // Element class can define custom element reactions
    constructor() { super(); }
    connectedCallback() {
      super.connectedCallback();
      console.log('x-foo created!');
    }
  }

  window.customElements.define(XFoo.is, XFoo);
</script>
</dom-module>

<x-foo>
  <h1>A logo</h1>
  <img />
</x-foo>

Share styles between elements

<dom-module id="my-style-module"> 
  <template> 
    <style> 
      <!-- Styles to share go here! --> 
    </style> 
  </template> 
</dom-module>

<!-- another element -->
<dom-module id="new-element"> 
  <template> 
    <style include="my-style-module"> 
      <!-- Any additional styles go here --> 
    </style> 
    <!-- The rest of your element template goes here --> 
  </template> 
</dom-module>

custom-style

兼容性写法,使用<custom-style>标签包围main document里面的全局<style>能避免在不支持shadowDOM v1规范的浏览器中全局css规则继续在shadowDOM中生效。 注意是避免CSS规则生效,而不是避免CSS样式的继承 custom-style元素不包含在Polymer中,需要引入:

<link rel="import" href="components/polymer/lib/elements/custom-style.html">

CSS custom properties

主要是提供一个支持两个CSS Next语法的扩展版本:

custom properties & var()
  • 可以通过——customvar形式定义变量,然后通过var(--customvar,[defaultvar])取值。
  • 通过这个特性我们可以暴露出一些可配置的变量,然后供组件外部的父元素进行自定义。
  • 与cssnext规范不同的是,cssnext的变量定义必须写在:root{}中,而Polymer则是不能在LightDOM中使用。
p {
  color: var(--paper-red-500);
}
paper-checkbox {
  --paper-checkbox-checked-color: var(--paper-red-500);
}

custom properties set & @apply

Polymer默认不支持自定义属性集合,需要手动引入:

<!-- import CSS mixins polyfill -->
<link rel="import" href="/bower_components/shadycss/apply-shim.html">
相当于cssnext对应的语法,但是同样可以在任何css Rule下使用。
<dom-module id="my-element"> 
  <template> 
    <style> 
      /* Apply custom theme to toolbars */ 
      :host { 
        --my-toolbar-theme: { 
          background-color: green; 
          border-radius: 4px; 
          border: 1px solid gray; 
        }; 
        --my-toolbar-title-theme: { 
          color: green; 
        }; 
      } 
      /* Make only toolbars with the .warning class red and bold */ 
      .warning { 
        --my-toolbar-title-theme: { 
          color: red; 
          font-weight: bold; 
        }; 
      } 
    </style> 
    <my-toolbar title="This one is green."></my-toolbar> 
    <my-toolbar title="This one is green too."></my-toolbar> 
    <my-toolbar class="warning" title="This one is red."></my-toolbar> 
  </template> 
  <script> 
    class MyElement extends Polymer.Element { 
      static get is() { 
        return "my-element"; 
      } 
    } 
    customElements.define(MyElement.is, MyElement); 
  </script> 
</dom-module> 

<dom-module id="my-toolbar"> 
  <template> 
    <style> 
      :host { 
        padding: 4px; 
        background-color: gray; 
        /* apply a mixin */ 
        @apply --my-toolbar-theme; 
      } 
      .title { 
        @apply --my-toolbar-title-theme; 
      } 
    </style> 
    <span class="title">{{title}}</span> 
  </template> 
  ... 
</dom-module>

CSS Custom Property API

updateStyles

动态更改css自定义属性的值。

<dom-module id="x-custom">
  <template>
    <style>
      :host {
        --my-toolbar-color: red;
      }
    </style>
    <my-toolbar>My awesome app</my-toolbar>
    <button on-tap="changeTheme">Change theme</button>
  </template>
  <script>
    class XCustom extends Polymer.Element {
      static get is() {
        return "x-custom";
      }
      static get changeTheme() {
        return function() {
        this.updateStyles({
          '--my-toolbar-color': 'blue',
        });
      }
    }
    customElements.define(XCustom.is, XCustom);
  </script>
</dom-module>
注意当外层元素或者被继承元素里面已经定义了一个变量,那么当前再定义这个变量是无效的,需要手动调用该方法。这个行为类似于Less

getComputedStyle(ShadyCSS.getComputedStyle)

获得当前自定义属性的值(需要区分原生和Polyfill)

if (ShadyCSS) { 
  style = ShadyCSS.getComputedStyleValue('--something'); 
} else { 
  style = getComputedStyle(this, '--something'); 
} 

DOM Templating

By default, adding a DOM template to an element causes Polymer to create a shadow root for the element and clone the template into the shadow tree.

DOMTemplate是通过clone操作添加到shadow tree里面去的。 有三种方式定义一个DOM Template:

template标签

直接将模板写在<template>标签里面, 是最直接的方式、最常见的方式。

<dom-module id="x-foo"> 
<template>I am x-foo!</template> 
<script> 
    class XFoo extends Polymer.Element { 
      static get is() { return  'x-foo' } 
    } 
    customElements.define(XFoo.is, XFoo); 
</script> 
</dom-module> 

String template

字符串模板

class MyElement extends Polymer.Element { 

static get template() { 
    return `<style>:host { color: blue; }</style> 
       <h2>String template</h2> 
       <div>I've got a string template!</div>` 
  } 
} 
customElements.define('my-element', MyElement); 

Retrieve or generate your own template element

通过继承或手动实现template getter获得模板. 注意: 1. 不要对父类的template直接修改,应该先拷贝一份出来。 2. 如果需要做一些耗资源的操作,应该对你修改的template进行缓存,以免重复调用。

(function() { 
  let memoizedTemplate; 

class MyExtension extends MySuperClass { 
    static get template() { 
      if (!memoizedTemplate) { 
        // create a clone of superclass template (`true` = "deep" clone) 
        memoizedTemplate = MySuperClass.template.cloneNode(true); 
        // add a node to the template. 
        let div = document.createElement('div'); 
        div.textContent = 'Hello from an extended template.' 
        memoizedTemplate.content.appendChild(div); 
      } 
      return memoizedTemplate; 
    } 
  } 

})(); 

URLs in template

默认对于所有从其他文件里面引入的组件里面元素所包含的链接Polymer是不做处理的,所有的相对路径的资源最后都是相对于主文档(main document)的路径。 但是我们可以使用下面两个特殊的标记

importPath

A static getter on the element class that defaults to the element HTML import document URL and is overridable. It may be useful to override importPath when an element's template is not retrieved from a  or the element is not defined using an HTML import.

一个静态getter函数,默认指向该元素被HTML import时候的URL,也可以被重写。

rootPath

An instance property set to the value of Polymer.rootPath which is globally settable and defaults to the main document URL. It may be useful to set Polymer.rootPath to provide a stable application mount path when using client side routing.

一个实例化的属性,值被设置为Polymer.rootPath。代表着主文档(main document)的URL。

Relative URLs in styles are automatically re-written to be relative to the importPath property. Any URLs outside of a <style> element should be bound using importPath or rootPath where appropriate.

所有style标签里面的URL全部被重写为相对于importPath的路径。除此之外,都需要自己手动添加合适的前缀:

<img src$="[[importPath]]checked.jpg"> 

<a href$="[[rootPath]]users/profile">View profile</a>

Static node map

Polymer builds a static map of node IDs when the element initializes its DOM template, to provide convenient access to frequently used nodes without the need to query for them manually. Any node specified in the element's template with an id is stored on the this.$ hash by id. The this.$ hash is created when the shadow DOM is initialized. In the ready callback, you must call super.ready() before accessing this.$.

这个主要是Polymer提供的一个可以快速访问DOM节点的方式。可以通过this.$[id]来获取拥有对应id的元素/自定义元素。
相当于document.getElementById的升级版类似于react中的this.refs
this.$接口只能在ready回调函数的super.ready()之后被调用。
动态创建的节点(dom-repeat\ dom-if)并不包含在this.$集合里,但是还是可以用标准的querySelector方法获取。

<dom-module id="x-custom"> 

<template> 
    Hello World from <span id="name"></span>! 
  </template> 

<script> 
    class MyElement extends Polymer.Element { 
      static get is() { return  'x-custom' } 
      ready() { 
        super.ready(); 
        this.$.name.textContent = this.tagName; 
      } 
    } 
  </script> 

</dom-module>

Polymer 2.0 文档笔记(3) Events

Normal Events

Polymer elements can use the standard DOM APIs for creating, dispatching, and listening for events. Polymer also provides annotated event listeners, which allow you to specify event listeners declaratively as part of the element's DOM template.

Add annotated event listeners

这个其实就是在标签上使用on-event属性。

<dom-module id="x-custom"> 
  <template> 
    <button on-click="handleClick">Kick Me</button> 
  </template> 
  <script> 
    class XCustom extends Polymer.Element { 

static get is() {return 'x-custom'} 

handleClick() { 
console.log('Ow!'); 
} 
} 
customElements.define(XCustom.is, XCustom); 
     </script> 
</dom-module> 
需要注意的有:

  1. 如果添加了手势事件则应当使用on-tap事件代替on-click事件,提供更好的移动浏览器支持。
  2. 因为html属性的限制,所有的事件名称都将转化为小写字母。(To avoid confusion, always use lowercase event names. )

Add and remove listeners imperatively

直接使用原生的addEventListenerremoveEventListener

Fire custom events

直接使用原生的CustomEventdispatchEvent

Event Retargeting

  1. 为了保持ShadowDOM的隐蔽性。元素内部ShadowDOM触发的一些事件在网上传播时会将target重定向到当前元素。
  2. event.composedPath() : 包含事件传递过程中所经过的nodes路径列表。 

自定义的事件默认无法穿透ShadowDOM边界。可以如下设置:

var event = new CustomEvent('my-event', {bubbles: true, composed: true});

Gesture Events

手势事件的支持是基于Legacy Element的,如果使用Polymer2的class风格定义需要使用mixin:Polymer.GestureEventListeners

<link rel="import" href="polymer/lib/mixins/gesture-event-listeners.html"> 

<script> 
    class TestEvent extends Polymer.GestureEventListeners(Polymer.Element) { 
      ... 
</script> 
注册事件也有两种方式: 1. 支持on-event形式的声明方式 2. 显示定义的方式:Polymer.Gestures.addListener(this, 'tap', e => this.tapHandler(e));

包含以下几种手势事件,包含在e.detail中。

  • down—finger/button went down
  • x—clientX coordinate for event
  • y—clientY coordinate for event
  • sourceEvent—the original DOM event that caused the down action
  • up—finger/button went up
  • x—clientX coordinate for event
  • y—clientY coordinate for event
  • sourceEvent—the original DOM event that caused the up action
  • tap—down & up occurred
  • x—clientX coordinate for event
  • y—clientY coordinate for event
  • sourceEvent—the original DOM event that caused the tap action
  • track—moving while finger/button is down
  • state—a string indicating the tracking state:
    • start—fired when tracking is first detected (finger/button down and moved past a pre-set distance threshold)
    • track—fired while tracking
    • end—fired when tracking ends
  • x—clientX coordinate for event
  • y—clientY coordinate for event
  • dx—change in pixels horizontally since the first track event
  • dy—change in pixels vertically since the first track event
  • ddx—change in pixels horizontally since last track event
  • ddy—change in pixels vertically since last track event
  • hover()-a function that may be called to determine the element currently being hovered

Polymer 2.0 文档笔记(4) Data System

Polymer提供观察函数、计算属性、数据绑定三大模型功能:

  • Observers Callbacks invoked when data changes.
  • Computed properties Virtual properties computed based on other properties, and recomputed when the input data changes.
  • Data bindings Annotations that update the properties, attributes, or text content of a DOM node when data changes.

```html

```

Observable Change

The data system is based on paths, not objects, where a path represents a property or subproperty relative to the host element.

Polymer的数据系统是基于数据的 路径 之上的。并不是实际的对象。

可观察到的变化指的是Polymer里面存在一个相关的路径指向这个数据的变化。因此,直接改变一个object、array等引用对象不会被观察到。

this.address.street = 'Elm Street'
改变address.street并不能被address上的观察器捕捉到变化

Mutating objects and arrays observably

使用Polymer提供的方法:

// 改变object
this.set('address.street','Half Moon Street') 
// 改变array
this.set('users.3',{name:'Hawking'})
this.push('users',{name: 'Maturin'}) 
this.pop('users')
this.unshift('users',{name: 'Martin'})
this.shift('users')
this.splice('users',3,1,{name:'Hawking'})

// 批量更新
this.setProperties({item:'Orange', count:12},true) //setReadOnly:true 代表需要设置ready-only的属性
//延迟统一更新
this.notifyPath('address.street') 
this.notifySplices('users') //only array

// 获得路径代表的属性值
var value = this.get('address.street') 
 //获得users[2]的值
var item = this.get(['users',2])

Polymer performs dirty checking for objects and arrays using object equality. It doesn't produce any property effects if the value at the specified path hasn't changed.

notifyPath方式需要提供具体属性的路径,而不应该是Object或Array,因为Polymer直接使用数据引用地址进行比较。如果一定需要观察它们,Polymer提供了三种解决方案:

  1. 使用Immutable之类的库,或者每次改变Object和Array里面的值的时候都先克隆出一个副本,在克隆的副本上修改然后把路径指向克隆副本。
  2. 使用mixin Polymer.MutableData可以禁止Polymer的对object和array的脏检查(dirty check)
  3. 使用mixin Polymer.OptionalMutableData可以在标签上添加一个bool属性mutable,代表是否对object或array开启脏检测

Data Paths

A data path is a series of path segments. In most cases, each path segment is a property name. The data APIs accept two kinds of paths: - A string, with path segments separated by dots. - An array of strings, where each array element is either a path segment or a dotted path.

数据路径可以是一个路径字符串,也可以是一个包含路径字符串的数组,比如下面三行全部代表同一个路径:

"one.two.three"
["one", "two", "three"]
["one.two", "three"]

data-path

Polymer doesn't automatically know that these properties refer to the same object.<address-card> makes a change to the object, no property effects are invoked on <user-profile> For data changes to flow from one element to another, the elements must be connected with a data binding.

Polymer是以路径来监听数据变化的。所以,就算两个路径实际上都指向同一个对象,他俩也不会联动。需要对这两个路径进行链接操作。

Linking paths with data bindings

data binding is the only way to link paths on different elements

<dom-module id="user-profile">
  <template><address-card
        address="{{primaryAddress}}"></address-card>
  </template></dom-module>
链接两个路径之后的示意图: data-binding

The <user-profile> element has a property primaryAddress that refers to a JavaScript object. The <address-card> element has a property address that refers to the same object. The data binding connects the path "primaryAddress" on <user-profile> to the path "address" on <address-card>

Data binding scope

Paths are relative to the current data binding scope. The topmost scope for any element is the element's properties. Certain data binding helper elements (like template repeaters) introduce new, nested scopes. For observers and computed properties, the scope is always the element's properties.

  1. 上面所说的路径都是相对于当前数据绑定(data-binding scope)定的。
  2. 最外层的域就是当前元素的本身(this),但一些数据绑定辅助元素(比如: template repeaters)可以创建新的子域。
  3. 观察函数(observers)和计算属性computed properties的域永远都是当前元素本身(this)

Special paths

  1. 通配路径(Wildcard paths)-可以使用通配符*来表示当前路径下的所有子路径的任何变化。比如users指向一个数组,users.*代表该数组的所有变化
  2. splices- 可以用在数组路径后面,代表数组任何添加、删除的变化
  3. 数组路径后面接下标代表数组里面对应的项,比如users.12

注意:

  1. 通配符只能用在observers、computed properties里面的路径中,不能用在数据绑定里
  2. 观察splices路径时,事件参数中只提供当前数组发生变化的元素组成的子数组,所以在一般情况下通配符路径比splices路径要实用

Two paths referencing the same object

如果两条路径都指向同一个对象,如下图,需要使用linkPaths方法将它们关联起来。 two-paths 注意:

  1. 两条路径必须在同一个data scope下
  2. 如果需要接触两条路径的关联,使用unlinkPaths, 该函数只接受linkPaths调用时的第一条路径

Data flow

Polymer implements the mediator pattern, where a host element manages data flow between itself and its local DOM nodes. When two elements are connected with a data binding, data changes can flow downward, from host to target, upward, from target to host, or both ways. When two elements in the local DOM are bound to the same property data appears to flow from one element to the other, but this flow is mediated by the host. A change made by one element propagates up to the host, then the host propagates the change down to the second element.

Polymer的数据流是一个中间人模型。任何存在数据绑定的两个元素直接的数据流都不是表面上的直接传递的,而是先向上传递(upward)到host元素再向下传递(downward)到目标元素。

Data flow is synchronous. When your code makes an observable change, all of the data flow and property effects from that change occur before the next line of your JavaScript is executed, unless an element explicitly defers action (for example, by calling an asynchronous method).

Polymer的数据传递是同步的,除非调用一个外部异步函数

How data flow is controlled

数据流的方向主要由两个地方控制:数据绑定方式和属性配置项。

数据绑定主要有两种方式: - Automatic :双向绑定,包括向上(upward,target to host)和向下(downward.host to target),使用 \{\{ \}\}

<my-input value="{{name}}"></my-input>

  • One-way :单向绑定,仅向下(downward.host to target),使用[[ ]]
    <name-tag name="[[name]]"></name-tag>
    
    属性配置项具体有两项:
  • notify 允许数据向上(upward,target to host)传递,默认为false
  • readOnly 禁止数据向下(downward.host to target)传递到当前组件,默认false

属性配置实例:

properties: {
  // default prop, read/write, non-notifying.
  basicProp: {
  },
  // read/write, notifying
  notifyingProp: {
    notify: true
  },
  // read-only, notifying
  fancyProp: {
    readOnly: true,
    notify: true
  }
}
注意: 1. 当使用单向绑定的时候,notify配置项无效。 2. 当单向绑定且readOnly:true时,将没有任何数据流

Property configuration only affects the property itself, not subproperties. In particular, binding a property that's an object or array creates shared data between the host and target element. There's no way to prevent either element from mutating a shared object or array.

属性配置不能继承

Data flow examples

参考:Data flow examples

Upward and downward data flow

Since the host element manages data flow, it can directly interact with the target element. The host propagates data downward by setting the target element’s properties or invoking its methods.

host元素可以直接通过设置target元素属性或调用回调函数等方法将数据向下传递给target元素

An element, host-element connected to an element, target-element by an arrow labeled 1.

Polymer elements use events to propagate data upward. The target element fires a non-bubbling event when an observable change occurs.

当数据是双向绑定的时候,target元素通过触发一个non-bubbling的change事件来将数据传递给监听这个事件的host元素,host元素监听到事件后对数据变化做出响应改变数据绑定模型(可能影响相邻元素)并触发另外一个change事件向上传播。

当数据是单向绑定的时候,host元素不会监听target元素的change事件,因此数据无法向上传递。

An element, target-element connected to an element, host-element by an arrow labeled 1. An arrow labeled 2 connects from the host element back to itself.

Data flow for objects and arrays

For object and array properties, data flow is a little more complicated. An object or array can be referenced by multiple elements, and there's no way to prevent one element from mutating a shared array or changing a subproperty of an object. As a result, Polymer treats the contents of arrays and objects as always being available for two- way binding. That is:

  • Data updates always flow downwards, even if the target property is marked read-only.
  • Change events for upward data flow are always fired, even if the target property is not marked as notifying.

Since one-way binding annotations don't create an event listener, they prevent these change notifications from being propagated to the host element.

对于objects和arrays绑定的数据流非常复杂,不得已Polymer将忽略关于它们所有的readyOnlynotify配置项,并将它们hardcode为true,单项绑定和双向绑定不受影响。

Change notification events

当一个元素某路径比如property发生变化,则会响应的触发一个property-changed的通知事件。 事件内容根据路径类型相关:

  1. 属性变化: 新值将储存detail.value
  2. 子属性变化:子属性的路径将会储存在detail.path中,新值将会储存在detail.value中。
  3. 数组变化:变化路径将会储存在detail.path中(比如: myArray.splices),新值将会被储存在detail.value中。

Don't stop propagation on change notification events. To avoid creating and discarding event objects, Polymer uses cached event objects for change notifications. Calling stopPropagation on a change notification event prevents all future events for that property. Change notification events don't bubble, so there should be no reason to stop propagation.

注意: 不要在通知事件里面使用stopPropagation

Custom change notification events

一些Native元素比如<input>并不存在变化通知事件,因此也不能将数据向上传递。可以通过下面的方式手动自定义一个变化通知事件:

<input value="{{firstName::change}}">

In this example, the firstName property is bound to the input's value property. Whenever the input element fires its change event, Polymer updates the firstName property to match the input value, and invokes any associated property effects. The contents of the event aren't important.

This technique is especially useful for native input elements, but can be used to provide two-way binding for any non-Polymer component that exposes a property and fires an event when the property changes.

Property effects

当属性变化的时候,下面的任务会依次执行:

  1. 重写计算受到影响的属性的值 - 此步将会更新计算属性(computed properties)
  2. 更新数据绑定
  3. 更新host元素上面的html属性
  4. 执行观察事件observers
  5. 触发变化通知事件

Polymer 2.0 文档笔记(5) Observers && Computed Properites

有两种监听器:

  1. 简单监听器,只能监听单一的property
  2. 复杂监听器:可以监听一到多个property

每个监听器都有一个或多个 依赖 ,当依赖发生可监听的变化是,监听方法就会被调用。

Computed properties are virtual properties based on one or more pieces of the element's data. A computed property is generated by a computing function—essentially, a complex observer that returns a value.

计算属性顾名思义,是由一个返回某个值的计算函数算出来的属性。

Observers and element initialization

只有当元素初始值加载完毕并且至少有一个依赖的属性被定义(undefined => somevalue),监听器才会被调用。

Observers are synchronous

  1. 监听器的执行也是同步的
  2. 如果监听器调用比较频繁,影响效率,可以使用Polymer.Async库来将它放到异步任务队列里面去。
  3. Polymer不保证异步执行的监听器所传的参数是否是最新的

Simple observers

简单监听器需要在properties中需要监听的property里面注册。监听函数里面不能依赖其他任何property

Simple observers are fired the first time the property becomes defined (!= undefined), and on every change thereafter, even if the property becomes undefined.

简单监听器第一次触发在property被定义后(undefined => somevalue),在此之后,任何property变化(包括重新变回undefined)都会被调用。

Simple observers only fire when the property itself changes. They don't fire on subproperty changes, or array mutation.

简单监听器只会响应当前property的可观察变化(observable changes)

You specify an observer method by name. The host element must have a method with that name.

简单监听器的定义和实现(函数本身)必须一一对应,简单监听器的实现可以在当前class里面也可以继承自superclass也可以添加自mixin。

The observer method receives the new and old values of the property as arguments.

简单监听器接受两个参数: oldValue,newValue

Observe a property

class XCustom extends Polymer.Element {

  static get is() {return 'x-custom'; }

  static get properties() {
    return {
      active: {
        type: Boolean,
        // Observer method identified by name
        observer: '_activeChanged'
      }
    }
  }

  // Observer method defined as a class method
  _activeChanged(newValue, oldValue) {
    this.toggleClass('highlight', newValue);
  }
}

Complex observers

复杂监听器需要在this.observers数组里面注册,复杂监听器可以监听多条路径(依赖)

static get observers() {
  return [
    // Observer method name, followed by a list of dependencies, in parenthesis
    'userListChanged(users.*, filter)'
  ]
}
注册函数里面的参数有如下几种:

  • 一个简单的属性路径 (firstName).

  • 一个简单的子属性路径 (address.street).

  • 一个数组的变化结果路径 (users.splices).

  • 一个包含通配符的路径 (users.*).

函数被调用时所得到的参数依据监听的路径种类不同而不同:

  • 简单的属性或子属性,传参为新值
  • 数组变化路径,传参为描述变化详情的 变化记录 对象
  • 通配符路径,传参为 变化记录 对象以及变化的详细路径

Note that any of the arguments can be undefined when the observer is called.

监听函数中每次调用,任何一个参数都有可能是undefined

复杂监听器的参数只有新值没有旧值

Observe changes to multiple properties

class XCustom extends Polymer.Element {

  static get is() {return 'x-custom'; }

  static get properties() {
    return {
        preload: Boolean,
        src: String,
        size: String
    }
  }

  // Each item of observers array is a method name followed by
  // a comma-separated list of one or more dependencies.
  static get observers() {
    return [
        'updateImage(preload, src, size)'
    ]
  }

  // Each method referenced in observers must be defined in
  // element prototype. The arguments to the method are new value
  // of each dependency, and may be undefined.
  updateImage(preload, src, size) {
    // ... do work using dependent values
  }
}

Observe array mutations

数组变化路径的参数change record是一个对象,包含一个indexSplices数组,数组中的每一项表示一处变更记录,包含下面信息:

  • index. 变更其实的地方
  • removed. 被删除的数据
  • addedCount. 插入的数据长度
  • object: 一个指向新数据的数组(不是拷贝) //A reference to the array in question. 这句话不懂什么意思
  • type: 一个值为'splice'的字符串

注意: change record也许会为undefined

class XCustom extends Polymer.Element {

  static get is() {return 'x-custom'; }

  static get properties() {
    return {
      users: {
        type: Array,
        value: function() {
          return [];
        }
      }
    }
  }

  // Observe changes to the users array
  static get observers() {
    return [
      'usersAddedOrRemoved(users.splices)'
    ]
  }


  // For an array mutation dependency, the corresponding argument is a change record
  usersAddedOrRemoved(changeRecord) {
    if (changeRecord) {
      changeRecord.indexSplices.forEach(function(s) {
        s.removed.forEach(function(user) {
          console.log(user.name + ' was removed');
        });
        for (var i=0; i<s.addedCount; i++) {
          var index = s.index + i;
          var newUser = s.object[index];
          console.log('User ' + newUser.name + ' added at index ' + index);
        }
      }, this);
    }
  }

  ready() {
    super.ready();
    this.push('users', {name: "Jack Aubrey"});
  }
}

customElements.define(XCustom.is, XCustom);

通配符路径的参数是一个change record对象,包含:

  • path 监听器监听的路径
  • value 新值
  • base 通配符之前的路径所代表的对象

如果通配符路径监听到的是数组的变化,那么

  1. path则是该数组的路径(不包括.splices
  2. value里面则会包含一个indexSplices
<dom-module id="x-custom">
  <template>
    <input value="{{user.name.first::input}}"
           placeholder="First Name">
    <input value="{{user.name.last::input}}"
           placeholder="Last Name">
  </template>
  <script>
    class XCustom extends Polymer.Element {

      static get is() { return 'x-custom'; }

      static get properties() {
        return {
          user: {
            type: Object,
            value: function() {
              return {'name':{}};
            }
          }
        }
      }

      static get observers() {
        return [
            'userNameChanged(user.name.*)'
        ]
      }

      userNameChanged(changeRecord) {
        console.log('path: ' + changeRecord.path);
        console.log('value: ' + changeRecord.value);
      }
    }

    customElements.define(XCustom.is, XCustom);
  </script>
</dom-module>

Identify all dependencies

Observers shouldn't rely on any properties, sub-properties, or paths other than those listed as dependencies of the observer. This creates "hidden" dependencies

监听器不能依赖任何其他未被注册过的路径,否则: 1. 不能保证该路径是否已经初始化完成 2. 当该路径的属性发生变化时,无法触发当前监听器

For example:

static get properties() {
  return {
    firstName: {
      type: String,
      observer: 'nameChanged'
    },
    lastName: {
      type: String
    }
  }
}

// WARNING: ANTI-PATTERN! DO NOT USE
nameChanged(newFirstName, oldFirstName) {
  // Not invoked when this.lastName changes
  var fullName = newFirstName + ' ' + this.lastName;
  // ...
}

Note that Polymer doesn't guarantee that properties are initialized in any particular order.

Polymer不能保证属性之间的初始化顺序。

Computed properties

Computed properties are virtual properties computed on the basis of one or more paths. The computing function for a computed property follows the same rules as a complex observer, except that it returns a value, which is used as the value of the computed property.

计算属性定义跟复杂监听器类似,但是计算属性的计算函数需要返回一个值。

Define a computed property

计算属性需要在properties里面的property配置对象中使用computed键注册,注册语法跟复杂监听器一致。

<dom-module id="x-custom">

  <template>
    My name is <span>{{fullName}}</span>
  </template>

  <script>
    class XCustom extends Polymer.Element {

      static get is() { return 'x-custom'; }

      static get properties() {
        return {
          first: String,

          last: String,

          fullName: {
            type: String,
            // when `first` or `last` changes `computeFullName` is called once
            // and the value it returns is stored as `fullName`
            computed: 'computeFullName(first, last)'
          }
        }
      }

      computeFullName(first, last) {
        return first + ' ' + last;
      }
    }

    customElements.define(XCustom.is, XCustom);
  </script>

</dom-module>

另外见 : Computed Bindings

Dynamic observer methods

If the observer method is declared in the properties object, the method is considered dynamic: the method itself may change during runtime. A dynamic method is considered an extra dependency of the observer, so the observer re-runs if the method itself changes. For example:

如果一个监听器或者计算属性的方法被定义在了properties里面,那么我们可以动态的对这个方法进行覆盖、重写。 当方法发生变化的时候,新的简单监听器或计算属性会被立即触发或者被更新。

class NameCard extends Polymer.Element {

  static get is() {
    return 'name-card'
  }

  static get properties() {
    return {
      // Override default format by assigning a new formatter
      // function
      formatter: {
        type: Function
      },
      formattedName: {
        computed: 'formatter(name.title, name.first, name.last)'
      },
      name: {
        type: Object,
        value() {
         return { title: "", first: "", last: "" };
        }
      }
    }
  }

  constructor() {
    super();
    this.formatter = this.defaultFormatter;
  }

  defaultFormatter(title, first, last) {
    return `${title} ${first} ${last}`
  }
}
customElements.define('name-card', NameCard);

nameCard.name = { title: 'Admiral', first: 'Grace', last: 'Hopper'}
console.log(nameCard.formattedName); // Admiral Grace Hopper
nameCard.formatter = function(title, first, last) {
  return `${last}, ${first}`
}
console.log(nameCard.formattedName); // Hopper, Grace
计算属性formattedName的方法formatter发生变化的时候,尽管依赖name没有变化,但是该属性还是触发更新了。

因为动态监听器方法出于properties里面,因此会被看作一个依赖,一旦这个方法被定义,监听器就在初始化的时候触发,尽管其他依赖都没有被定义。

Add observers and computed properties dynamically

In some cases, you may want to add an observer or computed property dynamically. A set of instance methods allow you to add a simple observer, complex observer, or computed property to the current element instance.

使用js API来动态添加计算属性或监听器 - _createPropertyObserver - _createMethodObserver - _createComputedProperty

Add a simple observer dynamically

this._observedPropertyChanged = (newVal) => { console.log('observedProperty changed to ' + newVal); };
this._createPropertyObserver('observedProperty', '_observedPropertyChanged', true);
第三个参数代表这个方法(_observedPropertyChanged)是否应该被看作一个依赖

Add a complex observer dynamically

this._createMethodObserver('_observeSeveralProperties(prop1,prop2,prop3)', true);

第三个参数代表这个方法(_observeSeveralProperties)是否应该被看作一个依赖

Add a computed property dynamically

this._createComputedProperty('newProperty', '_computeNewProperty(prop1,prop2)', true);
第三个参数代表这个方法(_computeNewProperty)是否应该被看作一个依赖

Polymer 2.0 文档笔记(6) Data Binding

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)

Anatomy of a data binding

数据绑定有两种绑定方式:

<custom-element property-name=annotation-or-compound-binding ></custom-element>
<custom-element attribute-name$=annotation-or-compound-binding></custom-element>
  1. =绑定property,$=绑定attribute(href,style,...)
  2. annotation代表数据绑定标记: [[ ]]或者\{\{ \}\}
  3. compound-binding:包含标记的字符串: "my name is {{ name }}"

Bind to a target property

将target元素的name属性绑定到当前元素的my-Name属性。 注意驼峰式和dash式命名的转换规则(property name to attribute name mapping)

<target-element name="{{myName}}"></target-element>

Bind to text content

相当于绑定到target元素的textContent属性上

<dom-module id="user-view">
  <template>
    <div>[[name]]</div>
  </template>

  <script>
    class UserView extends Polymer.Element {
      static get is() {return 'user-view'}
      static get properties() {
        return {
          name: String
        }
      }
    }

    customElements.define(UserView.is, UserView);
  </script>
</dom-module>

<!-- usage -->
<user-view name="Samuel"></user-view>

Binding to text content is always one-way, host-to-target.

注意,文字节点的绑定永远都是单向的(host to target)

Bind to a target attribute

attribute绑定相当于

element.setAttribute(attr,value)
property绑定相当于

element.property = 'value'

因此,一些attribute同样可以使用property形式绑定:

<template>
  <!-- Attribute binding -->
  <my-element selected$="[[value]]"></my-element>
  <!-- results in <my-element>.setAttribute('selected', this.value); -->

  <!-- Property binding -->
  <my-element selected="{{value}}"></my-element>
  <!-- results in <my-element>.selected = this.value; -->
</template>
需要注意的是: attribute形式的数据绑定只能是单向的([[ ]])

Native properties that don't support property binding

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 the value of a numeric input. Or use another element such as iron-input or paper-input that handles two-way binding correctly.

<!-- class -->
<div class$="[[foo]]"></div>

<!-- style -->
<div style$="[[background]]"></div>

<!-- href -->
<a href$="[[url]]">

<!-- label for -->
<label for$="[[bar]]"></label>

<!-- dataset -->
<div data-bar$="[[baz]]"></div>

<!-- ARIA -->
<button aria-label$="[[buttonLabel]]"></button>

Logical not operator

可以在data-binding表达式前面添加!号取反

<template>
  <my-page show-login="[[!isLoggedIn]]"></my-page>
</template>
注意:

  1. 逻辑非只能用在单项绑定中使用
  2. 只能有一个!不能!!

Computed bindings

computed binding类似于computed property。

<div>[[_formatName(first, last, title)]]</div>

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,差异有下面几点:

  • computed binding的依赖路径是相对于元素当前的data scope的
  • computed binding的参数不仅可以有computed property那样的路径参数,也可以是单纯的字符串或者数字等
  • computed binding可以没有参数,这种情况下,函数只会被调用一次
  • computed binding函数要等所有的参数中的依赖全部初始化(!=undefined)之后才会执行
<dom-module id="x-custom">

  <template>
    My name is <span>[[_formatName(first, last)]]</span>
  </template>

  <script>
    class XCustom extends Polymer.Element {
      static get is() {return 'x-custom'}
      static get properties() {
        return {
          first: String,
          last: String
        }
      }
      _formatName(first, last) {
        return `${last}, ${first}`
      }

    }

    customElements.define(XCustom.is, XCustom);
  </script>

</dom-module>

Commas in literal strings: Any comma occurring in a string literal must be escaped using a backslash (\).

如果参数是字符串,那么字符串里面所有的逗号都要被转义

<dom-module id="x-custom">
  <template>
    <span>{{translate('Hello\, nice to meet you', first, last)}}</span>
  </template>
</dom-module>

Computed bindings are one-way. A computed binding is always one-way, host-to-target.

computed binding只能在单向绑定中使用

Compound bindings

可以在字符串里面或者textContent里面使用绑定标记

<img src$="https://www.example.com/profiles/[[userId]].jpg">

<span>Name: [[lastname]], [[firstname]]</span>
注意:

  1. undefined会输出成空字符串
  2. Compound binding永远是单向绑定,虽然你也可以使用\{\{ \}\}记号。

Binding to array items

To keep annotation parsing simple, Polymer doesn't provide a way to bind directly to an array item.

为了解析简单,Polymer无法直接绑定一个数组里面的元素

<!-- Don't do this! -->
<span>{{array[0]}}</span>
<!-- Or this! -->
<span>{{array.0}}</span>

有下面几种方法可以解决: - dom-repeat里面已经为每个数组里面的元素创建了一个子scope,因此可以直接binding - array-selector 同上,可以直接绑定一个元素或者被选择的元素集合 - 使用computed binding来间接绑定,见下面例子

<dom-module id="x-custom">

  <template>
    <div>[[arrayItem(myArray.*, 0, 'name')]]</div>
    <div>[[arrayItem(myArray.*, 1, 'name')]]</div>
  </template>

  <script>

    class XCustom extends Polymer.Element {

      static get is() {return 'x-custom'}

      static get properties() {
        return {
          myArray: {
            type: Array,
            value: [{ name: 'Bob' }, { name: 'Doug' }]
          }
        }
      }

      // first argument is the change record for the array change,
      // change.base is the array specified in the binding
      arrayItem(change, index, path) {
        // this.get(path, root) returns a value for a path
        // relative to a root object.
        return this.get(path, change.base[index]);
      },

      ready() {
        super.ready();
        // mutate the array
        this.unshift('myArray', { name: 'Susan' });
        // change a subproperty
        this.set('myArray.1.name', 'Rupert');
      }
    }

    customElements.define(XCustom.is, XCustom);
  </script>

</dom-module>

Two-way binding to a non-Polymer element

为了达到非Polymer元素上面的双向绑定,可以使用下面的标记:

target-prop="{{hostProp::target-change-event}}"
<!-- Listens for `input` event and sets hostValue to <input>.value -->
<input value="{{hostValue::input}}">

<!-- Listens for `change` event and sets hostChecked to <input>.checked -->
<input type="checkbox" checked="{{hostChecked::change}}">

<!-- Listens for `timeupdate ` event and sets hostTime to <video>.currentTime -->
<video url="..." current-time="{{hostTime::timeupdate}}">
基于约定大于配置的原理,如果target-prop的变化通知函数是target-prop-changed则该定义可以省略。

<!-- Listens for `value-changed` event -->
<my-element value="{{hostValue::value-changed}}">

<!-- Listens for `value-changed` event using Polymer convention by default -->
<my-element value="{{hostValue}}">

Polymer 2.0 文档笔记(7) Helper Element

Polymer提供一系列的自定义元素来简化一些共有的数据绑定逻辑:

  • dom-repeat 遍历显示数组
  • array-selector 数组选择器
  • dom-if 条件显示
  • dom-bind 自动绑定

2.0 tip. The data binding helper elements are bundled in to the backward-compatible, polymer.html import. If you aren't using the legacy import, you'll need to import the helper elements you're using.

为了向前兼容,polymer.html引入了所有的helper元素,而2.0的polymer.Element则要按照需要一个个手动引入。

体验I3之美

enter description here 先晒张日常桌面图。Gnome3用了半年了一直被其蹩脚的交互和层出不穷的Bug所折磨。虽然Gnome3很漂亮,很简洁,但是毕竟漂亮不能当饭吃。套餐这种东西虽然简单省事,但是终究不是为你所量身定制的,总有其中一样不合你口味。因此,我决定再次抛弃“开箱即用”的DE(Desktop Environment),在WM(Window Manager)的基础上自己打造一套适合自己的桌面环境。

斐波那契堆之Go实现

一个比二叉堆更高效的数据结构,但是实现起来非常复杂。本科的时候看《算法导论》的时候曾经研究过,不是很明白。今天终于对它有了一个比较清晰的了解。 enter description here

网易云音乐新API简述

新API采用了略微修改过的AES和RSA加密,主要用在登陆接口上,对新API进行简单的分析。

Url

估计会抓包的人都知道,Url中的api便成了weapi。比如手机登录: 原来是:http://music.163.com/api/login/cellphone/ 现在是:http://music.163.com/weapi/login/cellphone/

加密算法

核心过程如下:

 aesRsaEncrypt = function (text, pubKey, modulus, nonce) {
  const secKey = createSecretKey(16);  // 随机生成16位加密密钥
  return {
    params:  aesEncrypt(aesEncrypt(text, nonce), secKey),
    encSecKey: rsaEncrypt(secKey, pubKey, modulus)
  }
}

Pandorabox之透明代理

enter description here 先修改Lan接口,避免在无线中继的时候发生本地Lan接口与wwan接口发生冲突导致无法登陆路由器。

网络 -> Lan -> IPv4地址, 设置为 192.168.33.1更改之后需要重新连接一下网络。

透明代理使用shadowsocks-libevChinDNS实现。使用ssh登陆路由器,安装所需软件。

ssh [email protected]
opkg update
opkg install shadowsocks-libev luci-app-shadowsocks ChinaDNS luci-app-chinadns --force-checksum

这个版本的软件源有点问题,所以直接opkg install基本上都过不了sha256sum检测,所以需要加上--force-checksum参数强制忽略。两个luci界面都有zh-cn汉化包,为了节省路由器空间,就不装了。