客户端,然后()或其他?

时间:2014-03-29 17:47:52

标签: dart dart-async

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

而且,我怎么能阻止我的代码的执行,而没有事件被捕获?

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>

3 个答案:

答案 0 :(得分:2)

如果我理解正确,你想在按下按钮时从ft_get_pseudo()函数获取text.value,对吧?如果是这样,您需要创建一个new 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;
}

答案 1 :(得分: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));
  }
}

答案 2 :(得分: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}"));
}