We are planning to use web workers in an ionic 2 application. However ionic 2 uses ionic-app-scripts (https://github.com/ionic-team/ionic-app-scripts, we are using version 1.0.0) with webpack. We need to have a webworker typescript file that is compiled to JS but NOT bundled with the other files as main.js.
What we had in mind was to have a file name format such as
servicetest.worker.ts where the ".worker" file extension part will be identified and compiled from typescript to javascript but not bundled along with the other files.
Any advice on this is much appreciated as it seems that we have to customize the appscripts.
Kind of a really late answer but perhaps it may help someone else.
Take a look at https://www.javascripttuts.com/how-to-use-web-workers-with-ionic-in-one-go/
I followed that article but had to make some adjustments because I had to call a worker method on demand, not on the constructor.
On the ./src/assets folder create a new folder called workers where your worker.JS files will live. Yes JS not TS, as far as I know TypeScript files won't compile to an usable webworker.
Create a webworker. I'll paste the main code of my fuzzySearch webworker (./assets/workers/fuzzysearch-worker.js):
'use strict';
var pattern, originalList;
self.onmessage = function(event) {
// Receive a message and answer accordingly
pattern = event.data.pattern;
originalList = event.data.originalList;
self.doFuzzySearch();
};
self.doFuzzySearch = function() {
var filteredList;
console.time('internalFastFilter');
filteredList = self.fastFilter(originalList, (item) => self.hasApproxPattern(item.searchField, pattern));
console.timeEnd('internalFastFilter');
// Send the results back
postMessage({ filteredList: filteredList });
};
// The code above is purposely incomplete
On your .ts file declare the worker variable (usually above the constructor):
private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');
On the constructor:
constructor(/* Other injected dependencies here */
public ngZone: NgZone) {
this.searchWorker.onmessage = (event) => {
// Inside ngZone for proper ChangeDetection
this.ngZone.run(()=> {
this.dataList = event.data.filteredList;
console.timeEnd('searchWorker');
})
};
}
Finally, on your "action function", lets say doSearch:
doSearch(event) {
// ... extra code to do some magic
console.time('searchWorker');
this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });
// ... extra code to do some other magic
}
this.searchWorker.postMessage makes the call. All heavy loading operations are resolved inside the webworker.
Hope it helps.
Best regards.
Related
This might be a rather straighforward question but I am wondering how to get a variable from a TS file, namely extension.ts, to a python file. the extension.ts file is used to create a file picker. then i want the path of that file to be used in the python file.
Is there a way to obtain the variable from extension.ts by importing? the majority of the TS code code was generated from Yo (a scaffolding tool) when I created the extension. i see that the function is exported so that would make it importable in JS and other TS files I think but im not sure how I would import it to a python file, or if thats even the best solution in the first place.
I will post the extension.ts below:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "fileDialog" is now active!');
let disposable = vscode.commands.registerCommand('fileDialog.openFile', () => {
const options: vscode.OpenDialogOptions = {
canSelectMany: false,
openLabel: 'Open',
};
vscode.window.showOpenDialog(options).then(fileUri => {
if (fileUri && fileUri[0]) {
let path = (fileUri[0].fsPath);
}
});
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {}
Thank you!
I am trying to add unit tests to an old vanilla JS project via Jasmine. I've read a little about using a specRunner.html page, but I've been hoping to include this as a git hook of some sort, instead of manually opening and confirming on a webpage.
This app runs by linking to all of the scripts in the index.html. There are no modules. It makes use of a global variable all the services are tacked onto to run the app.
Here's my current test set up, but I'm looking to improve it.
uat.js // this was existing already
globalVar.myUAT = (function () {
// this code requires anotherObject for it's getInstance()
})();
module.exports = globalVar.myUAT; // I had to add this
uat.spec.js // this is all new
describe('my tests', () => {
let anotherObject;
beforeEach(() => {
anotherObject = {...}; // I'm stubbing the object here
}
it('should instantiate', () => {
spyOn(anotherObject, 'method').and.callFake(...);
let uatClass = require('./uat.js');
let uat = uatFile.getInstance(anotherObject);
expect(uat).toBeTruthy();
}
});
What improvements can I make? I hate the stubbing of anotherObject in my beforeEach. Should I abandon this and just stick with the specRunner solution?
I am trying to break my nodejs code up into as small of files as possible to keep things modular. I have an app.js that is needing to use another method that I have moved to utils.js. The utils file however has a method that has a requirement for another library.
Should my utils.js file be "requiring" dependencies or should all those go in my app.js?
// app.js
var utilities = require('./utilities');
..
return utilities.anotherMethod();
// utils.js
module.exports = {
producer: function () {
// Handle mapping of fields depending on the source system
return 'map fields'
},
anotherMethod: function () {
// I require another lib. Do I do that here or app.js?
var kafka = require('kafka-node');
}
};
Update: Regarding the close request for an opinion based answer is essentially telling me that this can be done either way, which is what I was trying to clarify.
I am once again puzzled by Javascript. I am using Systemjs as a module loader and have a class as follows:
export default class Tool{
constructor(state, displayText) {
this._state = state;
this._displayText = displayText;
}
get displayText() {
return this._displayText;
}
get state() {
return this._state;
}
}
I am using this class in a unit test (Karma/Mocha/Chai) as follows:
'use strict';
import Tool from '../core/model/framework/Tool';
import chai from '../../../jspm_packages/npm/chai#3.5.0';
chai.should();
describe('MenuProvider', () => {
describe('registration', () => {
it('should register a new Workbench Module', ()=> {
let tools = [];
debugger;
tools.push(new Tool('Pink Fuzzy Bunnies', 'bunnyState'));
tools.push(new Tool('Look no hands', 'nohandsstate'));
let toolboxes = [];
toolboxes.push(new Toolbox('My Shiny New Toolbox', tools));
let newModule = new WorkbenchModule('My Module', toolboxes);
let providerUnderTest = new MenuProvider();
providerUnderTest.loadModule(newModule);
provider.modules.count.should.equal(1);
provider.getModule('My Module').should.not.be.null;
});
});
});
When I hit the debugger statement Tool is undefined. I am pretty sure I have jspm configured properly for my Karma test. I can see that every file is loading correctly when I debug the Karma test.
Is there something I am missing? I would just like to be pointed in the right direction. Let me know if I need to add more of my code or config.
You aren't exporting your class. Add this to the bottom of your Tool file:
export default Tool;
I was in fact exporting my class on the first line. The problem turned out to be related to the fact that Javascript does not hoist classes. Basically the tests were trying to use the classes before they were loaded by Karma and JSPM. I was able to resolve the issue by explicitly loading the files by adding the following to my config file:
jspm: {
config: 'jspm.conf.js',
loadFiles: ['src/app/angular-bootstrap.js', 'src/app/core/model/**/*.js', 'src/app/**/*.spec.js'], //'src/app/**/!(*.e2e|*.po).js'
serveFiles: ['src/app/**/*.+(js|html|css|json|*jade*)'] // *.{a,b,c} to *.+(a|b|c) https://github.com/karma-runner/karma/issues/1532
}
This is what did the trick: 'src/app/core/model//*.js'
Just as a tangential note. I also had fits over why Karam was not loading my Jade files so I could import them using JSPM. All I had to do was add the .jade extension to the list of file types being served up by Karma.
Such as a strange and wonderful world this Javascript stuff is!
I am currently developing a web application where we are using the Model View Controller method for organizing our information and code. In our case we are combining the View and Controller into one Javascript file and the Model is separate.
My question comes here. I've got prototype objects in my model, but I want to instantiate instances of these objects in my viewcontroller Javascript file. How do I get them talking to each other?
There are some ways to achieve that. Today, the simplest one would be:
<script src='model.js'></script>
<script src='view-controller.js'></script>
So, since your model.js will be loaded first, you can use it inside the view/controller.
Another way is by using modules. The most used today is RequireJS. E.g:
require(['model'], function(model) {
// This function is called when model.js is loaded.
// If model.js calls define(), then this function is not fired until
// model's dependencies have loaded, and the model argument will hold
// the module value for model.js.
});
ECMAScript 6 (the next version of Javascript), will have native modules, so you'll be able to do:
import * as model from './model'
var x = model.variable; // etc
You might also want to look into using Browserify if you are familiar with Node and RequireJS as you an also use NPM modules in the front-end.
http://browserify.org/
Browserify allows you to export your JS code from one file and require it in another (simplified idea).
file 1: myfunc.js
var myFunc = function(){
console.log("I'm an exported function that's in another file");
};
module.exports = myFunc;
file 2: app.js
var myFunc = require('./myfunc.js');
myFunc(): // logs "I'm an exported function that's in another file"