DEV Community

loading...

Reacting to streams

artydev profile image artydev ・1 min read

We have now our basic stream, how can we react on it ?
Always with simplicity in mind, here is a solution among others.


function Stream (value) {
  let storedvalue = value
  let mappers = []
  function stream (newvalue) {
    if (arguments.length) {
      mappers.map(f => f(newvalue))
      storedvalue = newvalue
    }
    return storedvalue
  }
  stream.map = function (f) {
    mappers.push(f)
  }
  return stream
}

s = Stream()

document.addEventListener("mousemove", s)

s.map(t => divmouse.innerHTML = (`<h2>(${t.clientX}, ${t.clientY})</h2>`)) 

You can test it here reactions

Discussion (2)

pic
Editor guide
Collapse
simpleadam profile image
simpleAdam

this is really useful in helping me understand streams, something which I did not understand before. Thankyou.

Collapse
artydev profile image
artydev Author

Hy Adam,
I am very glad it helped you, that is exactly why I post ;-)
Regards