Emitting custom event - javascript

I am using my custom yeoman generator programmatical in one of my nodejs module. I have written an Adapter to replace default TerminalAdapter.
The issues are,
When I am triggering custom event using emit method, I am not able
to listen for that event in my module. It is not getting fired.
Even end event listener also not getting fired.
Please let me know what I am missing here,
Below is my module code,
'use strict';
var fs = require('fs');
var path = require('path');
var MyOwnAdapter = require('./MyOwnAdapter');
var adapt = new MyOwnAdapter();
var env = require('./generator-myframewrk/node_modules/yeoman-generator')(null, {}, adapt);
env.register(path.resolve(__dirname, './generator-myframewrk'), 'myframewrk');
exports.run = function (options, answers) {
var obj = {};
adapt.setAnswers(answers);
process.chdir(options.projdir);
env.on("end", function(){
this.log("Even this is not getting called !!!"); //not coming here
}.bind(this));
env.on("alldone", function(){
this.log("Everything is done (including Bower install)"); //not coming here
obj.cb();
}.bind(this));
env.run('myframewrk', function(){
this.log('ran yo myframewrk, But bower install might be pending'); //coming here
});
return {
done: function (cb) {
obj.cb = cb;
}
};
};
Below is my Generator code,
var MyframewrkGenerator = yeoman.generators.Base.extend({
init: function () {
this.pkg = require('../package.json');
this.on('end', function () {
if (!this.options['skip-install']) {
this._installBower();
}
});
},
_installBower: function () {
this.log("Running bower install...");
/*reads bower.json and installs*/
bower.commands.install([], {}, {directory : "./"}).on('error', function (error) {
this.log("BOWER error::");
this.log(JSON.stringify(error));
}.bind(this)).on('log', function (log) {
this.log("BOWER LOG::"); // coming here
}.bind(this)).on('end', function (installed) {
this.log("BOWER END::"); // coming here
this.emit("alldone"); // my custom event
}.bind(this));
},
askFor: function () { ...

I took _installBower method out of this.on('end', function () {}); and made it a separate async func. This works fine. I don't need custom event anymore!
Thx...
bowerInstallHelper: function(){
if (!this.options['skip-install']) {
var cb = this.async();
this._installBower(cb);
}
}

Related

node js self this call method

I'm working on NodeJS and I have this module:
Manager.js
with this code (this is not all the code...):
//
// Object Manager
function Manager(params) {
client = new ModbusRTU();
}
//connessione alla seriale per lettura modbus
Manager.prototype.connectClient = function(){
// try to connect
client.connectRTUBuffered ("/dev/ttyS3", { baudRate: 19200 })
.then(function()
{
mbsState = MBS_STATE_GOOD_CONNECT;
mbsStatus = "Connected, wait for reading...";
console.log(mbsStatus);
})
.catch(function(e)
{
mbsState = MBS_STATE_FAIL_CONNECT;
mbsStatus = e.message;
console.log("Error:"+e);
});
client.setTimeout (20);
}
//read data
Manager.prototype.readData = function(){
var self = this;
client.setID(2);
// try to read data
client.readCoils (0, 7, function(error,data){
if(!error){
self.checkEmergency();
}
});
}
//emergency
Manager.prototype.checkEmergency= function(){
}
exports.Manager=Manager;
client part of code is about a modbus application.
When I try to call "self.checkEmergency()" from readData, I have this error:
"self.checkEmergency() is not a function"
Why?
The method readData is called inside a method like this:
Manager.prototype.caller= function(){
var self = this;
self.readData();
}
I also have used self to pass the object to the callback...
Any idea?

How to access the property of a function from module.exports

I have the following code in my index.js
const test = require('./js/lerifier/start');
const $ = require("jquery");
$( document ).ready(function() {
console.log( "ready!" );
console.log(test.init());
});
I want to access the this.init() function from the lerifier function on start.js
const $ = require("jquery");
const SVGInjector = require('svg-injector');
module.exports = function Verifier() {
this.init = function () {
let mySVGsToInject = $('img.inject-me');
let injectorOptions = {
evalScripts: 'once',
pngFallback: 'assets/png',
each: function (svg) {
// Callback after each SVG is injected
console.log('SVG injected: ' + svg.getAttribute('id'));
}
};
// Trigger the injection
SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
// Callback after all SVGs are injected
console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
});
}
};
With the code stated in the index.js the error msg that I get is
test.init is not a function, I know I'm doing something wrong or misunderstand the use of module.exports.
How about something like this. In this case there is a reference directly to the function in the start.js
const test = require('./js/lerifier/start.js').Verifier;

How to get utility function from helper file on node.js server?

I have a node/express server and I'm trying to get a function from a helper file to my app.js for use. Here is the function in the helper file:
CC.CURRENT.unpack = function(value)
{
var valuesArray = value.split("~");
var valuesArrayLenght = valuesArray.length;
var mask = valuesArray[valuesArrayLenght-1];
var maskInt = parseInt(mask,16);
var unpackedCurrent = {};
var currentField = 0;
for(var property in this.FIELDS)
{
if(this.FIELDS[property] === 0)
{
unpackedCurrent[property] = valuesArray[currentField];
currentField++;
}
else if(maskInt&this.FIELDS[property])
{
//i know this is a hack, for cccagg, future code please don't hate me:(, i did this to avoid
//subscribing to trades as well in order to show the last market
if(property === 'LASTMARKET'){
unpackedCurrent[property] = valuesArray[currentField];
}else{
unpackedCurrent[property] = parseFloat(valuesArray[currentField]);
}
currentField++;
}
}
return unpackedCurrent;
};
At the bottom of that helper file I did a module.export (The helper file is 400 lines long and I don't want to export every function in it):
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
Then in my app.js I called
var helperUtil = require('./helpers/ccc-streamer-utilities.js');
and finally, I called that function in app.js and console.log it:
res = helperUtil.unpackMessage(message);
console.log(res);
The problem is that the console.log gives off an undefined every time, but in this example: https://github.com/cryptoqween/cryptoqween.github.io/tree/master/streamer/current (which is not node.js) it works perfectly. So I think I am importing wrong. All I want to do is use that utility function in my app.js
The unPackMessage(val) call doesn't return anything:
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
you need to return CCC.CURRENT.UNPACK(value);
module.exports = {
unpackMessage: function(value) {
return CCC.CURRENT.unpack(value);
}
}

Replace attributes of a document in publish function

I'm using meteor and I have a question about the publish function (server side)
Meteor.publish('users', function () { .... }
I'm sending now documents to the browser which have id's of other collections. For example the Task document belongs to a project
{
title: '....',
projectId: 'KjbJHvJCHTCJGVY234',
...
}
What I want is to add a property to the this document projectTitle so I don't have to look up the project on the client. However, when I add this property in the publish function it is not send to the client. This is what I've tried:
Meteor.publish('tasks', function () {
var tasks = Tasks.find();
tasks.forEach(function (task) {
var project = Projects.findOne({_id: task.projectId});
task.projectTitle = project.title;
});
return tasks;
}
Any suggestions how to modify documents (not persistent) inside the publish function?
You could do this:
Meteor.publish("tasks", function() {
var transform = function(task) {
var project = Projects.findOne({_id: task.projectId});
task.projectTitle = project.title;
return task;
}
var self = this;
var tasks = Tasks.find().observe({
added: function (document) {
self.added('tasks', document._id, transform(document));
},
changed: function (newDocument, oldDocument) {
self.changed('tasks', document._id, transform(newDocument));
},
removed: function (oldDocument) {
self.removed('tasks', oldDocument._id);
}
});
self.ready();
self.onStop(function () {
tasks.stop();
});
});
There's a lot of custom logic there, but the 'transform' basically adds the attributes in.
Your code looks good but you're forgetting the .fetch() method on your task request. It should be var tasks = Tasks.find().fetch();

Start object from setInterval?

I have the following reconnect method for Sockjs which almost is fully working:
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
clearInterval(connectRetry);
$('.connect-status')
.removeClass('disconnected')
.addClass('connected')
.text('Connected');
};
warbleSocket.onmessage = function(e) {
$('#warble-msg').text(e.data);
};
warbleSocket.onclose = function() {
clearInterval(connectRetry);
connectRetry = setInterval(connectToServer, 1000);
$('.connect-status')
.removeClass('connected')
.addClass('disconnected')
.text('Disconnected');
};
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
var connectRetry = setInterval(connectToServer, 1000);
})();
The error i am getting is when its trying to reconnect.
Error is:
SyntaxError: missing ] after element list
at this line:
connectRetry = setInterval(connectToServer, 1000);
Any ideas what im doing wrong here?
Your connectToServer variable is not a function, it's an object with a property send that is a function, so it doesn't make sense to say setInterval(connectToServer, 1000). Try this instead:
setInterval(connectToServer.send, 1000);
Why don't you simplify things a bit?
I would put connection stuff inside a specific function and call it from setInterval().
Something like this (use with care since I'm not testing this code, ok?):
(function() {
// Initialize the socket & handlers
var connectToServer = function() {
var warbleSocket;
function connect() {
warbleSocket = new SockJS('http://url.com:5555/warble');
warbleSocket.onopen = function() {
// ...
};
warbleSocket.onmessage = function(e) {
// ...
};
warbleSocket.onclose = function() {
// ...
}
// Connect the text field to the socket
$('.msg-sender').off('input').on('input', function() {
warbleSocket.send($('.msg-sender input').val());
});
function send(a) {
warbleSocket.send(a);
}
return {
send: send
};
}();
// you probably will need to call the first connection
connectToServer();
// and than set connection retry
var connectRetry = setInterval(connectToServer.connect, 1000);
})();
I hope it helps you.
Regards,
Heleno

Categories

Resources