如何从Polymer Dart触发自定义事件?

Set*_*add 10 dart dart-polymer

我想从Polymer元素内部触发/发送/发出自定义事件.例如,我想将像"已更改"的普通DOM事件转换为更像"todoupdated"的语义事件.

这是我的HTML:

<polymer-element name="todo-item" extends="li" attributes="item">
  <template>
    <style>
      label.done {
        color: gray;
        text-decoration: line-through;
      }
    </style>
    <label class="checkbox {{item.doneClass}}">
      <input type="checkbox" checked="{{item.done}}">
      {{item.text}}
    </label>
  </template>
  <script type="application/dart" src="todo_item.dart"></script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

我希望复选框上的更改事件从自定义元素中冒出来,因为它更有用...... :)

Set*_*add 30

步骤1

捕获更改事件<input>.请注意on-change以下内容.

<!-- from inside todo_item.html -->
<input type="checkbox" checked="{{item.done}}" on-change="{{change}}">
Run Code Online (Sandbox Code Playgroud)

第2步

在包含复选框的自定义元素代码中处理change事件.

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'models.dart';

@CustomTag('todo-item')
class TodoItemElement extends PolymerElement with ObservableMixin {
  @observable Item item;

  bool get applyAuthorStyles => true;

  void change(Event e, var details, Node target) {
    // do stuff here
  }
}
Run Code Online (Sandbox Code Playgroud)

注意change事件处理程序.只要复选框状态发生变化,就会运行该方法.

第3步

发送自定义事件.

  void change(Event e, var details, Node target) {
    dispatchEvent(new CustomEvent('todochange'));
  }
Run Code Online (Sandbox Code Playgroud)

注意:自定义事件名称不得包含短划线.

第4步

在父自定义元素中侦听自定义事件.

    <template repeat="{{item in items}}" >
      <li is="todo-item" class="{{item.doneClass}}" item="{{item}}" on-todochange="todoChanged"></li>
    </template>
Run Code Online (Sandbox Code Playgroud)

注意使用on-todochange.

请享用!


Gün*_*uer 9

Polymer有一个辅助方法,可以简化触发事件

// dispatch a custom event
this.fire('polymer-select', detail: {'item': item, 'isSelected': isSelected});
Run Code Online (Sandbox Code Playgroud)

附加信息:
使订阅者可以以编程方式添加侦听器

// getter
async.Stream<dom.CustomEvent> get onPolymerSelect =>
    PolymerSelection._onPolymerSelect.forTarget(this);

// private EventStreamProvider
static const dom.EventStreamProvider<dom.CustomEvent> _onPolymerSelect =
    const dom.EventStreamProvider<dom.CustomEvent>('polymer-select');
Run Code Online (Sandbox Code Playgroud)

以编程方式而不是声明性地订阅事件:

($['#ps'] as PolymerSelect) // get the children and cast it to its actual type
    .onPolymerSelect.listen((e) => print(e['isSelected'])); // subscribe
Run Code Online (Sandbox Code Playgroud)