Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

How do I fire a custom event from Polymer Dart?

I want to fire/send/emit a custom event from inside a Polymer element. For example, I want to convert a normal DOM event like "changed" to a more semantic event like "todoupdated".

This is the HTML that I have:

<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>

I want the change events on checkbox to bubble out of the custom element as something more... useful. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Step 1

Capture the change events on the <input>. Notice the on-change below.

<!-- from inside todo_item.html -->
<input type="checkbox" checked="{{item.done}}" on-change="{{change}}">

Step 2

Handle the change event in the custom element code that contains the checkbox.

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
  }
}

Notice the change event handler. That method is run any time the checkbox state changes.

Step 3

Dispatch a custom event.

  void change(Event e, var details, Node target) {
    dispatchEvent(new CustomEvent('todochange'));
  }

NOTE: the custom event name must not contain dashes.

Step 4

Listen for the custom event in a parent custom element.

    <template repeat="{{item in items}}" >
      <li is="todo-item" class="{{item.doneClass}}" item="{{item}}" on-todochange="todoChanged"></li>
    </template>

Notice the use of on-todochange.

Enjoy!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...