1

我希望你能原谅我所期望的是一个真正的新手问题,但我一直无法找到解决这个问题的好方法......</p>

如果我有一个简单的课程......

library segmented_buttons_list;

import 'package:web_ui/observe.dart';

@observable
class SegmentedButtonData {
  String description;
  int index;

  SegmentedButtonData(this.description, this.index);

  String toString() => "$description";
}

...并从具有该类的 WebComponent 详细分派一个事件...

library segmented_buttons_list;

import 'dart:html';
import 'package:web_ui/web_ui.dart';
import 'package:segmented_buttons_list/segmented_button_data.dart';

class SegmentedButtonComponent extends WebComponent {
  int index;
  String description;

  mainAction() {
    SegmentedButtonData detail = new SegmentedButtonData(description, index);
    CustomEvent event = new CustomEvent("MainActionEvent", canBubble: true, cancelable: true, detail: detail);
    print("SegmentedButtonComponent dispatching ${event.type} for '${event.detail}'.");
    dispatchEvent(event);
  }
}

......我如何正确测试并使用该细节作为预期类型?

我尝试使用“is”,但在事件处理程序中不起作用......

if (event.detail is SegmentedButtonData) {
  SegmentedButtonData newSBD = event.detail;
  int newIndex = newSBD.index * 3;
  print(newIndex.toString());
}

…当我注释掉“如果”时,我得到了错误“类型'String'不是'newSBD'的'SegmentedButtonData'类型的子类型。”。

我尝试使用“as”,但也没有用。

似乎“详细信息”对象是一个字符串,即使我发送了一个 SegmentedButtonData 的实例。

我需要序列化/反序列化,还是我遗漏了一些细节?(哈哈)。

4

1 回答 1

0

因为 Dart CustomEvent 机制建立在标准 Web 浏览器事件之上,因此 Dart 之外的其他代码 (JavaScript) 可以捕获事件,因此 CustomEvent 的细节是有意序列化的。

这意味着为了获得最佳可预测性,最好手动序列化 CustomEvent 详细信息负载的数据,以便您可以放心地反序列化。

理论上你可以使用 Serialization 包来做到这一点,但它太过分了,我在反序列化时仍然遇到问题,或者你可以做一些简单的事情,比如使用 JSON(假设你的类属性主要是字符串、数字、列表和映射)。

数据类现在有一个toJson()功能......

library segmented_buttons_list;

import 'package:web_ui/observe.dart';

@observable
class SegmentedButtonData {
  String description;
  int index;

  SegmentedButtonData(this.description, this.index);

  String toString() => "$description";

  Map toJson() {
    return {"description": this.description, "index": this.index};
  }
}

...我们将数据对象序列化为 JSON 以添加到CustomEvent...

library segmented_buttons_list;

import 'dart:html';
import 'dart:json' as json;
import 'package:web_ui/web_ui.dart';

import 'package:segmented_buttons_list/segmented_button_data.dart';

class SegmentedButtonComponent extends WebComponent {
  int index;
  String description;

  mainAction() {
    SegmentedButtonData sbd = new SegmentedButtonData(description, index);
    String detail = json.stringify(sbd);
    CustomEvent event = new CustomEvent("MainActionEvent", canBubble: true, cancelable: true, detail: detail);
    dispatchEvent(event);
  }
}

...并在我们处理事件时反序列化以检查和使用事件详细信息...

Map detail = json.parse(event.detail);

if (detail is Map && detail.containsKey("description") && detail.containsKey("index")) {
  SegmentedButtonData newSBD = new SegmentedButtonData(detail["description"], detail["index"]);
  int newIndex = newSBD.index * 3;
  print(newIndex.toString());
}

希望这对某人有帮助。

于 2013-05-10T15:29:11.273 回答