Reputation: 79469
I'm writing a game in browser and I'm trying to find how to use .emit()
and .on()
methods in browsers. I can't get it to work as I get an error that .emit()
is undefined. Can anyone explain how to get it working?
For example, I'm trying to implement the following API for my game:
var game = new Game();
game.on('start', function(){
draw_players();
});
game.on('end', function(){
display_end_game_message();
});
etc.
And inside Game function I've something like this that emits start
:
function Game(){
function connect(){
emit('start');
}
}
How do I get emit()
and on()
working in browser?
Upvotes: 3
Views: 5937
Reputation: 127
instead of emit
and on
, you can use the events that are in the browser here.
They work similarly. Only they have addEventListener
instead of on
, and dispatchEvent
instead of emit
And for their work, you will need to create some kind of DOM-element
here is an example for your implementation
const gameEl = document.createElement('div')
const gameStartEvent = new Event('game-start')
gameEl.addEventListener('game-start', () => {
draw_players();
})
function Game(){
function connect(){
gameEl.dispatchEvent(gameStartEvent);
}
}
Upvotes: 1
Reputation: 845
Your problem is that the emit
and on
are node-specific functions that come with node libraries and only work when running your javascript server-side via Node.js
If you want to write your game using node, you should try out Browserify that will convert your node.js scripts to run on a browser.
Upvotes: 1