具有自定义事件和异步工作的自定义类,供浏览器使用

时间:2017-09-05 19:44:27

标签: javascript node.js javascript-events

我使用异步工作和自定义事件创建了一个简单的类。此版本适用于Node.js:

'use strict';
const EventEmitter = require('events');

// Custom class with the custom event and async work
class Foo extends EventEmitter{

    // Some async work with notifying
    doWork(data){

        const self = this;

        if(!data || 'number' != typeof data) {
            self.emit('work-done', new Error('Invalid data'));
            return;
        }
        else{

            // Some long work...
            function fib(n){
                return n < 2 ? n : fib(n - 1) + fib(n - 2);
            };

            // Start async work
            process.nextTick(function(){
                try{
                    const result = fib(data);
                    self.emit('work-done', null, result);
                }
                catch(err){
                    self.emit('work-done', err);
                }
            });
        }
    };
};

// Foo class using example
const foo = new Foo();
foo.on('work-done', (err, result) => {
    if(err) console.log(err);
    else console.log('Result: ' + result);
});

foo.doWork('jjjj'); // Error case
console.log();
foo.doWork(43); // Success case

console.log("Hello! Let's talk while I'm working.");
console.log('How are you?');
console.log();

它没有问题。我得到了结果:

Error: Invalid data
    at Foo.doWork (C:\nodejs\index.js:13:27)
    at Object.<anonymous> (C:\nodejs\index.js:44:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

Hello! Let's talk while I'm working.
How are you?

Result: 433494437

现在我想在我的JavaScript代码中使用我的Foo类,它将由Web浏览器使用。如何为这个porpose重写Foo类?我在代码中要做哪些更改?

0 个答案:

没有答案