document.cookie = "test=demo"; // worker获取主线程资源 var CookieAction = BI.inherit(BI.Workers.WorkerBaseAction, { addActionHandler: function() { this.controller.addActionHandler("Cookie", this.getCookie.bind(this)); }, getCookie: function() { return document.cookie; } }); // 调用worker计算 var FibonacciAction = BI.inherit(BI.Workers.WorkerBaseAction, { addActionHandler: function() {}, getResult: function(times) { return this.controller.requestPromise("Fibonacci", { times: times }) .then(function(v) { console.log(v); }); } }); // 主线程与worker多次交互 const HeartBeatCheckAction = BI.inherit(BI.Workers.WorkerBaseAction, { addActionHandler: function() { this.controller.addActionHandler("HeartBeatChecked", this.recieveHeartBeatChecked.bind(this)); }, recieveHeartBeatChecked: function (payload) { console.log("heartbeat: " + payload.time); }, startHeatBeatCheck: function() { return this.controller.request("HeartBeatCheckStart"); }, stopHeatBeatCheck: function() { return this.controller.request("HeartBeatCheckStop"); } }); var MainThreadWorker = BI.inherit(BI.Workers.MainThreadWorker, { initActions: function() { this.cookieAction = this.createAction(CookieAction); this.fibonacciAction = this.createAction(FibonacciAction); this.heartBeatCheckAction = this.createAction(HeartBeatCheckAction); }, calculateFibonacci: function(times) { this.fibonacciAction.getResult(times); }, startHeatBeatCheck: function() { this.heartBeatCheckAction.startHeatBeatCheck(); }, stopHeatBeatCheck: function() { this.heartBeatCheckAction.stopHeatBeatCheck(); } }); var mainThreadWorker = BI.Workers.createWorker(MainThreadWorker, { workerUrl: "./worker_new/worker.js", workerName: "demo" }); BI.createWidget({ type: "bi.vertical", element: "#wrapper", vgap: 10, hgap: 10, items: [ { type: "bi.button", text: "点击计算斐波那契数列第40项", width: 200, handler: function() { console.log("click"); mainThreadWorker.calculateFibonacci(40); } }, { type: "bi.button", text: "开始心跳", width: 200, handler: function() { mainThreadWorker.startHeatBeatCheck(); } }, { type: "bi.button", text: "停止心跳", width: 200, handler: function() { mainThreadWorker.stopHeatBeatCheck(); } } ] });