1

我如何在客户端使用“未来”?

而且,我如何阻止我的代码的执行,而没有事件被捕获?

import 'dart:html';
import 'dart:convert';
import 'dart:async';

Map data;

Future<String> ft_get_pseudo()
{
  InputElement button;
  InputElement text;

  text = querySelector('[name="pseudo"]');
  button = querySelector('[name="push"]');
  button.onClick.listen((_) => text.value);
}

void    main()
{
    WebSocket wss;
  String encode;

  data = new Map();
    wss = new WebSocket('ws://127.0.0.1:4040/ws');
  ft_get_pseudo().then((name)
  {
    data['pseudo'] = name;
    encode = JSON.encode(data);
    wss.onOpen.listen((_) => wss.send(encode));
    wss.onMessage.listen((msg) => print("Msg received : ${msg.data}"));
  });
}

我在 ecmascript 6 中看到了 Promise 函数,有没有使用它的方法,或者想法?

HTML:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script type="application/dart" src="client.dart"></script>
    <link rel="stylesheet" href="style.css" type="text/css">
    <title>Client</title>
</head>
<body>
<div id="console">
</div>
<input type="text" name="pseudo" size="20" placeholder="pseudo">
<input type="button" name="push" value="Send">
</body>
</html>
4

3 回答 3

2

对于这样一个简单的用例,您可以这样做

Future<String> ft_get_pseudo()
{
  return new Future(() {
    InputElement button;
    InputElement text;

    text = querySelector('[name="pseudo"]');
    button = querySelector('[name="push"]');
    button.onClick.listen((_) => _completer.complete(text.value));
  }
}
于 2014-03-30T08:30:45.263 回答
2

如果我理解正确,您想在按下按钮时从 ft_get_pseudo() 函数中获取 text.value ,对吗?如果是这样,您需要创建一个新的 Completer并在 ft_get_pseudo() 的末尾返回它的 Future。然后,在按钮的 onClick 事件中,您只需使用 text.value 的值完成未来。

代码可能是这样的:

Future<String> ft_get_pseudo()
{
  Completer _completer = new Completer();

  InputElement button;
  InputElement text;

  text = querySelector('[name="pseudo"]');
  button = querySelector('[name="push"]');
  button.onClick.listen((_) => _completer.complete(text.value));

  return _completer.future;
}
于 2014-03-30T08:00:04.250 回答
1

我认为你想做这样的事情,但我还不完全理解你试图完成什么。您能否仅添加评论您需要的不同之处?

Map data;

void main() {
  //(querySelector('[name="push"]') as ButtonInputElement).onClick.listen(btnClickHandler);
  (querySelector('[name="push"]') as ButtonInputElement).onClick.first.then(btnClickHandler);

  // this would work too, because every element has the click event.
  // querySelector('[name="push"]').onClick.listen(btnClickHandler);
}

void btnClickHandler(MouseEvent e) {
  String name = (querySelector('[name="pseudo"]') as TextInputElement).value;    

  data = {'pseudo': name}; 
  String encode = JSON.encode(data);

  WebSocket wss = new WebSocket('ws://127.0.0.1:4040/ws');
  wss.onOpen.listen((_) => wss.send(encode));
  wss.onMessage.listen((msg) => print("Msg received : ${msg.data}"));
}
于 2014-03-30T14:21:15.733 回答