How to use ember-pusher in ember-cli project - ember.js

pusher in ember-cli project. I am sorry but i find if difficult to get my head around js tools.
Ember pusher github
steps done so for.
Inside ember-cli project: bower install --save pusher
In broccoli.js file added line: app.import('vendor/pusher/dist/pusher.js');
in .jshintrc
"predef": {
"document": true,
"window": true,
"MyappENV": true,
"Pusher": true
}
Then copied ember-pusher.amd.js from git mentioned link and saved in /vendor folder.
In broccoli.js file added line:
var App = Ember.Application.extend({
modulePrefix: 'Myapp', // TODO: loaded via config
Resolver: Resolver,
PUSHER_OPTS: {
key: '586f8kjhfkdf8d7f9',
connection: {},
logAllEvents: true
},
});
5.In app.js.
var App = Ember.Application.extend({
modulePrefix: 'Myapp',
Resolver: Resolver,
PUSHER_OPTS: {
key: '586f8kjhfkdf8d7f9',
connection: {},
logAllEvents: true
}
});
6. In application.js controller
import Ember from 'ember';
export
default Ember.Controller.extend({
PUSHER_SUBSCRIPTIONS: {
myChannel: ['my-event']
},
actions: {
myEvent: function () {
console.log('Event my event was triggered xxxxxxxxxxxxxxxxxxx');
}
}
});
I donot get any error message but pusher dashboard does not show any connections
app.import('vendor/ember-pusher/ember-pusher.amd.js', {
exports: {
'ember-pusher': [
'controller',
'binding',
'clientevents',
'initialize'
]
}
});

There is now an ember addon for this, with instructions in the README: https://github.com/ivanvotti/ember-cli-pusher

Here's what I did to get it working:
bower install --save pusher
Download ember-pusher.js to vendor/ember-pusher/ember-pusher.js from https://github.com/jamiebikies/ember-pusher#download
Add the following to your Brocfile.js
app.import('bower_components/pusher/dist/pusher.js');
app.import('vendor/ember-pusher/ember-pusher.js');
Add the following to config/environment.js
ENV.APP.PUSHER_OPTS = { key: 'your-app-key', connection: { } }
Log events from one of your controllers
import Ember from 'ember';
export default Ember.Controller.extend(EmberPusher.Bindings, {
logPusherEvents: true,
PUSHER_SUBSCRIPTIONS: {
myChannel: ['my-event']
}
}

Related

How can i load changes to my code in a Vue app?

I deployed a Django+VueJS app that uses django webpack loader in order to render Vue apps in my Django templates. I used Nginx and Gunicorn to deploy the app to a DigitalOcean VPS, everything works without any problem but i have some doubts on how to edit my components in production, since i'm fairly new to Vue
Here is my vue.config:
const BundleTracker = require("webpack-bundle-tracker");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const pages = {
'main': {
entry: './src/main.js',
chunks: ['chunk-vendors']
},
}
module.exports = {
pages: pages,
runtimeCompiler: true,
filenameHashing: false,
productionSourceMap: false,
publicPath: process.env.NODE_ENV === 'production'
? 'static/vue'
: 'http://localhost:8080/',
outputDir: '../django_vue_mpa/static/vue/',
chainWebpack: config => {
config.optimization
.splitChunks({
cacheGroups: {
moment: {
test: /[\\/]node_modules[\\/]moment/,
name: "chunk-moment",
chunks: "all",
priority: 5
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "chunk-vendors",
chunks: "all",
priority: 1
},
},
});
Object.keys(pages).forEach(page => {
config.plugins.delete(`html-${page}`);
config.plugins.delete(`preload-${page}`);
config.plugins.delete(`prefetch-${page}`);
})
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]);
// Uncomment below to analyze bundle sizes
// config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin);
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://localhost:8080')
.host('localhost')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["*"]})
}
};
So in order to deploy the Vue part i did npm run build and npm created a bunch of files in my static directory. Now, every time i edit a component, in order to see the changes on the web, i do npm run build every time, which takes some time. Is this how am i supposed to do it? Or is there a shorter way?
I don't know about django, But I know about vue..
is this how am I supposed to do it?
For me, I don't suggest it, you can use your django as a backend for your frontend
that should mean you would have 2 servers running. 1 for your django and 1 for your vue app. use XHR request to access your django App, remember to handle CORS. IMHO I don't want vue to be used as a component based framework.
is there a shorter way.
YES, and this is how you do it.
add to package.json
{
...,
scripts: {
...,
'watch' : 'vue-cli-service build --watch --inline-vue',
...,
}
}
while using the following settings in vue.config.js
module.exports = {
'publicPath': '/django/path/to/public/folder',
'outputDir': '../dist',
'filenameHashing': false,
runtimeCompiler: true,
'css': {
extract: true,
},
}
i forgot about how publicPath and outputDir works..
but you can check it out here https://cli.vuejs.org/config/#publicpath
regarding the code on the package.json file..
you can check it here
https://github.com/vuejs/vue-cli/issues/1120#issuecomment-380902334

bootstrap#4.0.0-beta install issue for the Ember js [duplicate]

I am trying to install properly Twitter Bootstrap in my current ember-cli project.
I did install bootstrap with bower :
bower install --save bootstrap
Now the library is downloded in /vendor/bootstrap/dist/(css|js|fonts)
I tried what is mentioned here : http://ember-cli.com/#managing-dependencies
replacing path and css files names but I get errors regarding the Brocfile.js file. I think the brocfile format has changed too much compared to the example.
I also tried to #import with the /app/styles/app.css file after moving the stylesheets in the /app/styles/ directory :
#import url('/assets/bootstrap.css');
#import url('/assets/bootstrap-theme.css');
But it did not work. The files are visible true dev server : http://localhost:4200/assets/bootstrap.css
Can someone throw me a bone here ?
Thx
Edit :
ember -v
ember-cli 0.0.23
brocfile.js
/* global require, module */
var uglifyJavaScript = require('broccoli-uglify-js');
var replace = require('broccoli-replace');
var compileES6 = require('broccoli-es6-concatenator');
var validateES6 = require('broccoli-es6-import-validate');
var pickFiles = require('broccoli-static-compiler');
var mergeTrees = require('broccoli-merge-trees');
var env = require('broccoli-env').getEnv();
var getEnvJSON = require('./config/environment');
var p = require('ember-cli/lib/preprocessors');
var preprocessCss = p.preprocessCss;
var preprocessTemplates = p.preprocessTemplates;
var preprocessJs = p.preprocessJs;
module.exports = function (broccoli) {
var prefix = 'caisse';
var rootURL = '/';
// index.html
var indexHTML = pickFiles('app', {
srcDir: '/',
files: ['index.html'],
destDir: '/'
});
indexHTML = replace(indexHTML, {
files: ['index.html'],
patterns: [{ match: /\{\{ENV\}\}/g, replacement: getEnvJSON.bind(null, env)}]
});
// sourceTrees, appAndDependencies for CSS and JavaScript
var app = pickFiles('app', {
srcDir: '/',
destDir: prefix
});
app = preprocessTemplates(app);
var config = pickFiles('config', { // Don't pick anything, just watch config folder
srcDir: '/',
files: [],
destDir: '/'
});
var sourceTrees = [app, config, 'vendor'].concat(broccoli.bowerTrees());
var appAndDependencies = mergeTrees(sourceTrees, { overwrite: true });
// JavaScript
var legacyFilesToAppend = [
'jquery.js',
'handlebars.js',
'ember.js',
'ic-ajax/dist/named-amd/main.js',
'ember-data.js',
'ember-resolver.js',
'ember-shim.js',
'bootstrap/dist/js/bootstrap.js'
];
var applicationJs = preprocessJs(appAndDependencies, '/', prefix);
applicationJs = compileES6(applicationJs, {
loaderFile: 'loader/loader.js',
ignoredModules: [
'ember/resolver',
'ic-ajax'
],
inputFiles: [
prefix + '/**/*.js'
],
legacyFilesToAppend: legacyFilesToAppend,
wrapInEval: env !== 'production',
outputFile: '/assets/app.js'
});
if (env === 'production') {
applicationJs = uglifyJavaScript(applicationJs, {
mangle: false,
compress: false
});
}
// Styles
var styles = preprocessCss(appAndDependencies, prefix + '/styles', '/assets');
// Bootstrap Style integration
var bootstrap = pickFiles('vendor', {
srcDir: '/bootstrap/dist/css',
files: [
'bootstrap.css',
'bootstrap-theme.css'
],
destDir: '/assets/'
});
//var bootstrap = preprocessCss(appAndDependencies, '/vendor/bootstrap/dist/css', '/assets');
// Ouput
var outputTrees = [
indexHTML,
applicationJs,
'public',
styles,
bootstrap
];
// Testing
if (env !== 'production') {
var tests = pickFiles('tests', {
srcDir: '/',
destDir: prefix + '/tests'
});
var testsIndexHTML = pickFiles('tests', {
srcDir: '/',
files: ['index.html'],
destDir: '/tests'
});
var qunitStyles = pickFiles('vendor', {
srcDir: '/qunit/qunit',
files: ['qunit.css'],
destDir: '/assets/'
});
testsIndexHTML = replace(testsIndexHTML, {
files: ['tests/index.html'],
patterns: [{ match: /\{\{ENV\}\}/g, replacement: getEnvJSON.bind(null, env)}]
});
tests = preprocessTemplates(tests);
sourceTrees = [tests, 'vendor'].concat(broccoli.bowerTrees());
appAndDependencies = mergeTrees(sourceTrees, { overwrite: true });
var testsJs = preprocessJs(appAndDependencies, '/', prefix);
var validatedJs = validateES6(mergeTrees([app, tests]), {
whitelist: {
'ember/resolver': ['default'],
'ember-qunit': [
'globalize',
'moduleFor',
'moduleForComponent',
'moduleForModel',
'test',
'setResolver'
]
}
});
var legacyTestFiles = [
'qunit/qunit/qunit.js',
'qunit-shim.js',
'ember-qunit/dist/named-amd/main.js'
];
legacyFilesToAppend = legacyFilesToAppend.concat(legacyTestFiles);
testsJs = compileES6(testsJs, {
// Temporary workaround for
// https://github.com/joliss/broccoli-es6-concatenator/issues/9
loaderFile: '_loader.js',
ignoredModules: [
'ember/resolver',
'ember-qunit'
],
inputFiles: [
prefix + '/**/*.js'
],
legacyFilesToAppend: legacyFilesToAppend,
wrapInEval: true,
outputFile: '/assets/tests.js'
});
var testsTrees = [qunitStyles, testsIndexHTML, validatedJs, testsJs];
outputTrees = outputTrees.concat(testsTrees);
}
return mergeTrees(outputTrees, { overwrite: true });
};
BASH:
bower install --save bootstrap
Brocfile.js:
app.import('vendor/bootstrap/dist/js/bootstrap.js');
app.import('vendor/bootstrap/dist/css/bootstrap.css');
The JS will be added to the app.js, which is linked by default, and the CSS will be added to assets/vendor.css, which as of May 14th, is also added by default.
For reference: http://www.ember-cli.com/#managing-dependencies
In response to #Joe's question surrounding fonts and other assets, I was unable to get the recommended app.import() method to work on the fonts. I instead opted for the merge-trees and static-compiler approach:
var mergeTrees = require('broccoli-merge-trees');
var pickFiles = require('broccoli-static-compiler');
var extraAssets = pickFiles('vendor/bootstrap/dist/fonts',{
srcDir: '/',
files: ['**/*'],
destDir: '/fonts'
});
module.exports = mergeTrees([app.toTree(), extraAssets]);
BASH:
bower install --save bootstrap
Brocfile.js:
/* global require, module */
...
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/css/bootstrap.css.map', {
destDir: 'assets'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
module.exports = app.toTree();
You might want to check out ember-bootstrap, which will import the bootstrap assets automatically.
ember install ember-bootstrap
Moreover it adds a suite of native ember components to your app, that make working with bootstrap features much easier in ember. Check it out, although I am a bit biased, as I am the author of it! ;)
Update 3/30/15
plus ça change... I use ember-cli-bootstrap-sassy now, it seems to bring along minimum cruft while still letting me customize Bootstrap's variables.
Update 1/22/15
You should probably use Johnny's solution above instead of the lib I originally mentioned. I also like ember-cli-bootstrap-sass, because I can customize Bootstrap's variables directly in my project.
Original 7/11/14
If you're using a version of ember-cli that supports addons (0.35+, I believe), you can now use the ember-cli-bootstrap package. From the root of your app,
npm install --save-dev ember-cli-bootstrap
That's it!
Note: as #poweratom points out, ember-cli-bootstrap is somebody else's library which chooses to also include bootstrap-for-ember. Thus, this lib could get out of sync with official bootstrap version. However, I still find it a great way to get prototyping fast on a new project!
$> bower install --save bootstrap
Afterwards add following two lines to your ember-cli-builds.js (or Brocfile.js if you are using an older version of Ember.js):
app.import(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.js');
app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.css');
And voilà, ready to go!
updated 08/18/2015: adapted to new scheme introduced in Ember.js 1.13
If you're using SASS (probably via ember-cli-sass), bower_components is automatically added to the lookup path. This means you can just use Bower and avoid the Brocfile/ember-cli-build file altogether.
Install the official SASS version of Bootstrap with Bower
bower install --save bootstrap-sass
then import the lib in app.scss. The nice thing about this is you can customize the variables before importing bootstrap:
$brand-primary: 'purple';
#import 'bower_components/bootstrap-sass/assets/stylesheets/bootstrap';
This is how I package vendor CSS files with Broccoli (which underpins Ember-cli).
var vendorCss = concat('vendor', {
inputFiles: [
'pikaday/css/pikaday.css'
, 'nvd3/nv.d3.css'
, 'semantic-ui/build/packaged/css/semantic.css'
]
, outputFile: '/assets/css/vendor.css'
});
Where the vendor folder is where my Bower packages live. And assets is where I'm expecting my CSS to live. I'm assuming you've installed Bootstrap using Bower, which is the Ember-cli way.
Then in my index.html, I'm simply referencing that vendor.css file:
<link href="/assets/css/vendor.css" rel="stylesheet" type="text/css" media="all">
Cheers.
bower install --save bootstrap
in your brocfile.js:
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
On the terminal (For those using Node Package Manager)
npm install bootstrap --save
Using ember-cli, to import your installed bootstrap
Open the ember-cli-build.js file
module.exports = function(defaults) {
let app = new EmberApp(defaults, {
// Add options here
});
app.import('node_modules/bootstrap/dist/css/bootstrap.min.css');
app.import('node_modules/bootstrap/dist/js/bootstrap.min.js');
That will do it if bootstrap is installed via the NPM installer.
Do not do this:
app.import('./node_modules/bootstrap/dist/css/bootstrap.min.css');
app.import('./node_modules/bootstrap/dist/js/bootstrap.min.js');

Ckeditor usage in Ember

I want to use CKEditor with my Ember app.
I am 100% a n00b with Ember, but I'm getting there.
I have tried my darndest to figure this out, but I've gotten nowhere :(
I have tried to use ember-ckeditor. This ended up with the editor throwing a bunch of net::ERR_NAME_NOT_RESOLVED errors for things such as config.js and other "assets" it expected to find in the assets folder.
I have tried ember-cli-ckeditor. Same exact issues as above.
These two addons have pretty lame documentation. For example, I have no idea how provide a custom config file, CSS, etc. Or what if I want to use CkFinder?
The two above addons also throw some depreciated warnings when loading up the server, but I disgress....
I finally tried to manually include ckeditor v4.5.6 in the vendor folder.
I then included in ember-cli-build.js as such: app.import('vendor/ckeditor/ckeditor.js');
I'm not sure if I'm correct in doing this, and if so, how do I include use the editor plugin within my controller or component?
CKEDITOR.replace("content"); as per usual outside of Ember?
Please school me!
To use ckeditor without addons (creating your own component):
Install ckeditor using bower:
bower install ckeditor --save
Install broccoli-funnel, you will need it for ckeditor's assets:
npm install broccoli-funnel --save-dev
In your ember-cli-build.js:
At the top of file requere funnel
var Funnel = require('broccoli-funnel');
In app's options exclude ckeditor's assets from fingerprinting:
var app = new EmberApp(defaults, {
fingerprint: {
exclude: ['assets/ckeditor/']
}
});
Import ckeditor's js and assets:
app.import('bower_components/ckeditor/ckeditor.js');
var ckeditorAssets = new Funnel('bower_components/ckeditor', {
srcDir: '/',
destDir: '/assets/ckeditor'
});
/**
* If you need to use custom skin, put it into
* vendor/ckeditor/skins/<skin_name>
* Also, custom plugins may be added in this way
* (look ckeditor's info for details)
* If you don't need custom skins, you may remove
* ckeditorCustoms
*/
var ckeditorCustoms = new Funnel('vendor/ckeditor', {
srcDir: '/',
destDir: '/assets/ckeditor'
});
return app.toTree([ckeditorAssets, ckeditorCustoms]);
If your app is not in website's root, you may need to put this script in body section of index.html, before other scripts:
<script type="text/javascript">
window.CKEDITOR_BASEPATH = '/path-to/assets/ckeditor/';
</script>
Create a component. Warning: this is a code from my abandoned pet project, and I'm 99% sure that it will not work for you "as is" because of missing dependencies and because it was created for different html layout. But I think it may help anyway. If you wish to try and copy-paste it, here are dependencies:
npm install --save-dev ember-browserify
npm install --save-dev sanitize-html
Component's code:
/* globals CKEDITOR */
import Ember from 'ember';
import layout from '../templates/components/md-ckeditor'; //component's name!
import SanitizeHTML from 'npm:sanitize-html';
export default Ember.Component.extend({
layout: layout,
classNames: ['input-field'],
_editor: null,
bindAttributes: ['disabled', 'readonly', 'autofocus'],
validate: false,
errorsPath: 'errors',
init() {
this._super(...arguments);
const propertyPath = this.get('valueBinding._label');
if (Ember.isPresent(propertyPath)) {
Ember.Binding.from(`targetObject.${this.get('errorsPath')}.${propertyPath}`)
.to('errors')
.connect(this);
}
},
didInsertElement() {
var i18n = this.get('i18n');
if (Ember.isPresent(this.get('icon'))) {
this.$('> span').css('padding-left', '3rem');
}
this._setupLabel();
this._editor = CKEDITOR.inline(this.element.querySelector('.ckeditor'), {
skin: 'minimalist',
toolbar: [
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
['Undo', 'Redo'],
['Bold', 'Italic', 'Strike'],
['Link', 'Unlink'],
['NumberedList', 'BulletedList', 'Blockquote'],
['Source']
],
linkShowAdvancedTab: false,
linkShowTargetTab: false,
language: i18n.get('locale'),
removePlugins: 'elementspath'
});
this._editor.on('instanceReady', (e) => {
this._updateValidClass();
});
this._editor.on('change', (e) => {
this.set('value', e.editor.getData());
});
this._editor.on('focus', (e) => {
var label = this.$('> label, > i');
label.addClass('active');
});
this._editor.on('blur', (e) => {
var label = this.$('> label, > i');
var text = SanitizeHTML(e.editor.getData(), {
allowedTags: []
}).trim();
if (text !== '') {
label.addClass('active');
} else {
label.removeClass('active');
}
});
},
willDestroyElement()
{
this._editor.destroy();
this._editor = null;
},
id: Ember.computed('elementId', function () {
return `${this.get('elementId')}-input`;
}),
validClass: Ember.computed('value', 'errors', function () {
var errors = this.get('errors');
if (errors && errors.get && errors.get('firstObject')) {
return 'invalid';
} else if (!!this.get('value')) {
return 'valid';
} else {
return '';
}
}),
validClassChanged: Ember.observer('validClass', function () {
Ember.run.once(this, '_updateValidClass');
}),
_updateValidClass() {
if (this._editor && this._editor.container && this._editor.container.$) {
Ember.$(this._editor.container.$).removeClass('invalid valid').addClass(this.get('validClass'));
}
},
_setupLabel() {
const label = this.$('> label, > i');
if (Ember.isPresent(this.get('value'))) {
label.addClass('active');
}
}
});
Template:
{{textarea
id=id
value=value
name=name
required=required
readonly=readonly
disabled=disabled
maxlength=maxlength
class="materialize-textarea ckeditor"
classNameBindings="validate:validate: validClass"
}}
<label for="{{id}}">{{label}}</label>
<small class="red-text">
{{#if errors}} {{errors.firstObject}} {{else}} {{/if}}
</small>
Check next example
https://github.com/ebryn/ember-ckeditor/blob/master/addon/components/ember-ckeditor.js
Or next package ember-cli-ckeditor
https://www.npmjs.com/package/ember-cli-ckeditor

Initialize cloudinary_js v2 in Ember JS app

I'm trying to upload images to cloudinary from an EmberJS app (v2.6), following the post of Beerlington where it uses cloudinary_js (now with new API v2) and in order to install it :
npm install blueimp-file-upload --save
npm install cloudinary-jquery-file-upload --save
But when I'm trying to initialize the cloudinary the library is not recognized.
#app/initializers/cloudinary.js
export default {
name: 'cloudinary',
initialize: function(/* container, app */) {
jQuery.cloudinary.config({
cloud_name: ENV.CLOUDINARY_NAME
});
}
};
#console
TypeError: Cannot read property 'config' of undefined
Since ember.js is essentially a client side framework, you need to use bower libraries instead of npm (more).
Install Cloudinary using bower:
bower install cloudinary-jquery-file-upload --save
(blueimp will be installed as a dependency.)
Add the imports to your ember-cli-build.js file:
/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
app.import("bower_components/jquery/dist/jquery.js");
app.import("bower_components/blueimp-file-upload/js/vendor/jquery.ui.widget.js");
app.import("bower_components/blueimp-file-upload/js/jquery.iframe-transport.js");
app.import("bower_components/blueimp-file-upload/js/jquery.fileupload.js");
app.import('bower_components/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js');
return app.toTree();
};
Add jQuery to the global definitions in .jshintrc (showing fragment here):
{
"predef": [
"document",
"window",
"-Promise",
"jQuery",
"$"
],
"browser": true,
// rest of file...
}
Add cloudinary too if you intend to use the cloudinary namespace directly.
Now you can use Cloudinary and Blueimp in your code. For example:
import Ember from 'ember';
export default Ember.Route.extend(
{
model() {
$.cloudinary.config({"cloud_name": "your_cloud"});
$(document).ready(function () {
$(".cloudinary-fileupload").cloudinary_fileupload(
// etc.
)}
);
}
});

Ember-cli project and web workers

Ember-cli: 0.33
How can I use web workers within an ember-cli based project?
Example - I have a component and I want to start a web worker:
import Ember from 'ember';
export default Ember.Component.extend({
_startWorker: function() {
var worker = new Worker('path/to/worker.js');
}.on('didInsertElement')
});
In which folder should I put the worker.js file inside the ember-cli project structure?
Which other changes are required (Brocfile.js,...)?
One possible solution:
1) In your ember project root folder add a new folder with the name 'workers'.
2) Update your Brocfile.js (see Screenshot)
3) Write workers :-)
relevant code from #Steven's solution for easy copying:
/* 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);
If that helps someone, I managed to start using using workers with the config below, using ember-cli >= 2.4.2 to be able to use 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'});
});
Then the workers code:
//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});
});
}
};
Calling the workers from anywhere in your app:
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"});