AngularJS和网络工作者 [英] AngularJS and web workers
问题描述
如何angularJS使用网络工作者在后台运行的进程?有没有我应该遵循这样做呢?
How can angularJS use web workers to run processes in the background? Is there any pattern I should follow on doing this?
目前,我正在使用具有在一个单独的网络工作者模型的服务。这个服务实现方法一样:
Currently, I am using a service that has the model in a separate web worker. This service implements methods like:
ClientsFacade.calculateDebt(client1); //Just an example..
在实施方式中,此方法将消息发送到与数据的工人。这让我抽象的,它是在一个单独的线程中执行,我还可以提供,对,做在同一个线程此操作的服务器,甚至有人查询实现的事实。
In the implementation, this method sends a message to the worker with the data. This allows me to abstract the fact that it is being performed in a separate thread and I could also provide an implementation that queries against a server or even one that does this action in the same thread.
由于我是新来的JavaScript,我只是回收的知识,我从其他平台有我不知道如果这是你会怎么做或者角度这是我在用的,提供有几分这样的方式。这还介绍了我的架构的改变,因为工人必须明确地将更改推送到控制器,然后更新它的值,然后这反映在视图中,我是在这个工程?这是一个有点沮丧的是网络工作者保护了我这么多从没有让我分享内存等搞砸了。
Since I'm new to javascript and I'm just recycling knowledge I have from other platforms I wonder if this is something you would do or perhaps Angular which is what I am using, offers a sort of way of doing this. Also this introduces a change in my architecture since the worker must explicitly push changes to the controller, which then updates its values and then this is reflected in the view, am I over engineering this? It's a bit frustrating that web workers "protect" me so much from screwing up by not allowing me to share memory etc.
推荐答案
使用Web工人发生通信通过消息传递机制。拦截这些消息发生在回呼。在AngularJS,最好的位置放一个网络工作者是一种服务,你适当的注意。对付这一点,最好的方法是使用承诺,其中角工作得有。
Communication with Web workers happens through a messaging mechanism. Intercepting these messages happens in a call back. In AngularJS, the best location to put a web worker is in a service as you duly noted. The best way to deal with this is to use promises, which Angular works amazingly with.
下面是一个例子 webworker
在服务
var app = angular.module("myApp",[]);
app.factory("HelloWorldService",['$q',function($q){
var worker = new Worker('doWork.js');
var defer = $q.defer();
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
defer.resolve(e.data);
}, false);
return {
doWork : function(myData){
defer = $q.defer();
worker.postMessage(myData); // Send data to our worker.
return defer.promise;
}
};
});
现在无论外部访问的Hello World服务不需要关心的实现细节实体的HelloWorldService
- 的HelloWorldService
能可能处理过网络工作者
,在 HTTP
数据,或者做加工在那里。
Now whatever external entity that accesses Hello World service need not care about the implementation details of HelloWorldService
- HelloWorldService
could probably process the data over a web worker
, over http
or do the processing right there.
希望这是有道理的。
这篇关于AngularJS和网络工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!