由于AssemblyScript语言暂不支持闭包的限制,一定程度影响开发体验。Waft也在积极跟进社区提案,通过上层转译等方式解决。
目前需要通过下面的方式来解决闭包透传数据的问题:
如何在回调的闭包里透传数据
Case 1:this可以直接透传
import { Target } from "waft";export class Index extends Page {constructor(props: Props){super(props);}onLoad(query: JSONObject): void{// 页面加载后console.log('page onLoad:' + JSON.stringify(query));// setTimeout示例// 第三个参数,可以自定义传入透传(必须继承于Target)// 后会通过回调的第二个参数返回过来setTimeout((_, target)=>{console.log("timer fire");const _this = (target as Index);// _this.setState()},3000, this);// network示例const obj = new JSONObject();obj.set('url','https://xxx.xxx.com');obj.set('method','GET');network.request(obj.toString(), (result: JSONObject, target):void => {const _this = (target as Index);// _this.setState()}, this);}}
Case 2:复杂数据建议用class包裹
import { Target } from "waft";class DataBundle extends Target{dataString: string = "";}const bundle = new DataBundle();bundle.dataString = "xxxxxxxx";// setTimeout是前端框架自定义提供的函数// 第三个参数 bunlde 可以自定义传入透传(必须继承于Target)// 后会通过回调的第二个参数bundle返回过来setTimeout((_, bundle)=>{console.log("timer fire");const dataString = (bundle as DataBundle).dataString;},3000, bundle)const obj = new JSONObject();obj.set('url','https://xxx.xxx.com');obj.set('method','GET');network.request(obj.toString(), (result: JSONObject, target):void => {const dataString = (target as DataBundle).dataString;}, bundle);

