I've been reading a fair amount about advantages of functional programming, and am trying to write some code which adheres to what might be considered functional programming. Immutability, Pure Functions, Local States, etc.
The particular problem I have is as shown below. I'm not sure if there is some way to do what I want without breaking those rules. I guess I'm here to find that out.
let mouseDown = false;
document.addEventListener('mousedown', () => mouseDown = true);
document.addEventListener('mouseup', () => mouseDown = false);
document.addEventListener('mousemove', e => {
if (mouseDown) console.log({ x: e.movementX, y: e.movementY });
});
After spending 10+ years working with OOP, I'm finding it very hard to get a hand of FP. However, that's beside the point.
So, my questions are:
Rxjs will fit in here for the code
http://reactivex.io/rxjs/manual/overview.html
Normally you register event listeners.
var button = document.querySelector('button');
button.addEventListener('click', () => console.log('Clicked!'));
Using RxJS you create an observable instead.
var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
.subscribe(() => console.log('Clicked!'));
What makes RxJS powerful is its ability to produce values using pure functions. That means your code is less prone to errors.
Purity
var count = 0;
var button = document.querySelector('button');
button.addEventListener('click', () => console.log(`Clicked ${++count} times`));
Using RxJS you isolate the state.
var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
.scan(count => count + 1, 0)
.subscribe(count => console.log(`Clicked ${count} times`));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With