由于AssemblyScript语言暂不支持闭包的限制,一定程度影响开发体验。Waft也在积极跟进社区提案,通过上层转译等方式解决。

目前需要通过下面的方式来解决闭包透传数据的问题:

如何在回调的闭包里透传数据

Case 1:this可以直接透传

  1. import { Target } from "waft";
  2. export class Index extends Page {
  3. constructor(props: Props){
  4. super(props);
  5. }
  6. onLoad(query: JSONObject): void{
  7. // 页面加载后
  8. console.log('page onLoad:' + JSON.stringify(query));
  9. // setTimeout示例
  10. // 第三个参数,可以自定义传入透传(必须继承于Target
  11. // 后会通过回调的第二个参数返回过来
  12. setTimeout((_, target)=>{
  13. console.log("timer fire");
  14. const _this = (target as Index);
  15. // _this.setState()
  16. },3000, this);
  17. // network示例
  18. const obj = new JSONObject();
  19. obj.set('url','https://xxx.xxx.com');
  20. obj.set('method','GET');
  21. network.request(obj.toString(), (result: JSONObject, target):void => {
  22. const _this = (target as Index);
  23. // _this.setState()
  24. }, this);
  25. }
  26. }

Case 2:复杂数据建议用class包裹

  1. import { Target } from "waft";
  2. class DataBundle extends Target{
  3. dataString: string = "";
  4. }
  5. const bundle = new DataBundle();
  6. bundle.dataString = "xxxxxxxx";
  7. // setTimeout是前端框架自定义提供的函数
  8. // 第三个参数 bunlde 可以自定义传入透传(必须继承于Target
  9. // 后会通过回调的第二个参数bundle返回过来
  10. setTimeout((_, bundle)=>{
  11. console.log("timer fire");
  12. const dataString = (bundle as DataBundle).dataString;
  13. },3000, bundle)
  14. const obj = new JSONObject();
  15. obj.set('url','https://xxx.xxx.com');
  16. obj.set('method','GET');
  17. network.request(obj.toString(), (result: JSONObject, target):void => {
  18. const dataString = (target as DataBundle).dataString;
  19. }, bundle);

image.png