napajs icon indicating copy to clipboard operation
napajs copied to clipboard

Using prototype functions in napa

Open ciko92 opened this issue 7 years ago • 3 comments

I'm trying to use napajs with prototype functions. How can I bind 'this' inside the broadcast api? Moreover, I'm trying to require momentjs and toolbox inside broadcast, but it's not working.

ciko92 avatar May 22 '18 10:05 ciko92

How can I bind 'this' inside the broadcast api?

I don't get what's the question... could you share an example to help me understand?

I've tried the moment module. It works in this way -

const napa = require('napajs');
let z1 = napa.zone.create('z1', { workers: 1 });
z1.broadcastSync(()=>{
  let moment = require('moment');
  console.log(moment().format("MMM Do YY"));
});

This does not work:

z1.broadcastSync(()=>{
  let moment = require('moment');
});
z1.execute(()=>{
  console.log(moment().format("MMM Do YY")); //ReferenceError: moment is not defined
});

By using global it does work:

z1.broadcastSync(()=>{
  global.moment = require('moment');
});
z1.execute(()=>{
  console.log(global.moment().format("MMM Do YY"));
});

fs-eire avatar May 24 '18 01:05 fs-eire

Thank you fs-eire! Global works perfectly for me.

I have a class Greedy and some prototype functions that I need to broadcast such as Greedy.prototype.optimize = function(orders, moovers){ ... return solution}. I can't call z1.broadcastSync(this.optimize.toString()) inside others prototype functions. How can I do it?

ciko92 avatar May 25 '18 08:05 ciko92

In my previous attempt I always put definitions of customized class into a separated file. Say I have a file greedy.js with the definition of optimize() inside so I broadcast a call to require() to handle this kind of requirement.

fs-eire avatar Jun 11 '18 22:06 fs-eire