官术网_书友最值得收藏!

Basic web worker communication

As the component loads, we will want to set up the worker so that it is not something that we have to repeat several times. So, imagine if there were a way in which you can set up something conditionally and perform an action only when you want it to. In our case, you can add it to the constructor or to any of the lifecycle hooks that denote what phase the component is in such as OnInit, OnContentInit, OnViewInit and so on, which are provided by Angular as follows:

this.worker = new Worker('scripts.bundle.js');

this.worker.addEventListener('message', (e) => {
this.result = e.data;
});

Once initialized, we then use the addEventListener() method to listen for any new messages—that is, results coming from our worker.

Any time the code is changed, we simply pass that data to the worker that we have now set up. The implementation for this looks as follows:

codeChange() {
this.worker.postMessage(this.code);
}

As you can note, the main application component is intentionally lean. We are leveraging workers for the sole reason that CPU-intensive operations can be kept away from the main thread. In this case, we can move all the logic including the validations into the worker, which is exactly what we have done.

主站蜘蛛池模板: 襄城县| 菏泽市| 仙桃市| 翁源县| 鹤岗市| 海口市| 赤水市| 志丹县| 方城县| 大埔区| 清新县| 揭阳市| 调兵山市| 长阳| 什邡市| 杨浦区| 开远市| 柳河县| 皋兰县| 宿松县| 嘉峪关市| 安阳市| 昌平区| 镇平县| 汨罗市| 新兴县| 西青区| 宣化县| 烟台市| 息烽县| 温宿县| 嘉义县| 交城县| 扎鲁特旗| 浦江县| 长沙市| 韶山市| 大悟县| 钟山县| 鄂州市| 永年县|