Ember-cli项目和网络工作者

时间:2014-06-12 01:22:14

标签: ember.js web-worker ember-cli

Ember-cli:0.33

如何在基于ember-cli的项目中使用网络工作者?

示例 - 我有一个组件,我想启动一个Web worker:

import Ember from 'ember';
export default Ember.Component.extend({
  _startWorker: function() {
    var worker = new Worker('path/to/worker.js');
  }.on('didInsertElement')
});

我应该将worker.js文件放在ember-cli项目结构中的哪个文件夹中? 还需要哪些其他更改(Brocfile.js,...)?

3 个答案:

答案 0 :(得分:2)

一种可能的解决方案:

1)在您的ember项目根文件夹中添加一个名为' workers'的新文件夹。

2)更新你的Brocfile.js(见截图)

3)写工人: - )

Needed changes for webworkers support

答案 1 :(得分:2)

@ Steven的易于复制解决方案的相关代码:



/* global require, module, process */

var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var pickFiles = require('broccoli-static-compiler');

var app = new EmberApp();

var workers = pickFiles('workers', {
  srcDir: '/',
  files: ['*.js'],
  destDir: '/assets/workers'
});

if (process.env.EMBER_ENV === 'production') {
  workers = require('broccoli-uglify-js')(workers, {
    mangle: true,
    compress: true
  });
}

module.exports = app.toTree(workers);




答案 2 :(得分:0)

如果这对某人有帮助,我设法开始使用具有以下配置的工作人员,使用ember-cli> = 2.4.2来使用outputFile

//ember-cli-build.js
..
//don't prepend CDN to worker paths (or CORS issue)
fingerprint: {
  exclude: ['worker'],
  ..
}
..
var app = new EmberApp(defaults, {
  ..
  app.import('vendor/localforage.js');//use localforage outside of workers
  app.import('vendor/localforage.js',outputFile:'assets/workers/localforage.js'});//use localforage inside of workers
  app.import('vendor/worker_localforage.js',outputFile:'assets/workers/worker_localforage.js'});
  app.import('vendor/worker_test_indexeddb.js',outputFile:'assets/workers/worker_test_indexeddb.js'});
});

然后工人代码:

//vendor/worker_localforage.js
importScripts('localforage.js');

self.onmessage = function(e) {
  var namespace=e.data.namespace;
  var msg=e.data.msg;
  var data=e.data.data;
  //console.log("msg to worker",namespace,msg);
  if (msg==="load") {
    localforage.getItem(namespace).then(function(res){
      self.postMessage({msg:"load",data:res});
    });
  }
  else if (msg==="persist") {
    localforage.setItem(namespace,data).then(function(res){
      self.postMessage({msg:"persist",data:res});
    });
  }
};

从应用中的任何位置呼叫工作人员:

self.worker=new Worker("assets/workers/worker_localforage.js");
var worker=self.worker;
prom2= new Ember.RSVP.Promise(function(resolve,reject){
  worker.onmessage=function(e){
    if (e.data.msg==="load") {
      resolve(e.data.data);
    }
  }
});
worker.postMessage({namespace:self.adapterNamespace(),msg:"load"});