0

I am using

sources.DOM.select('document').events('keydown')
  .map(ev => Object.assign({}, ev, {type: 'keydown'}))

but the resulting stream gives objects with just the "isTrusted" property (and not "key", "code", etc.). Instead, with 'mousemove' I get events as expected (with "isTrusted" but also "movementX", "movementY", etc.). What is wrong?

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
cmant
  • 453
  • 1
  • 5
  • 11
  • [Works okay here.](https://codepen.io/bloodyKnuckles/pen/mQJwjN?editors=0010) What version Cycle DOM are you using? – bloodyKnuckles Nov 06 '18 at 01:28
  • Sorry, I edited the code in the question with the part that causes the problem (and I did not suspect it was). So the problem is Object.assign, that does not copy all the properties of the event object in the new object. It seems to me that, apart from "isTrusted", the properties of the event object are ignored both by Object.assign and JSON.stringify. Do you know why? – cmant Nov 06 '18 at 14:52

1 Answers1

1

You're right, not a Cycle.js problem but rather a limitation of Object.assign.

Simply put—Object.assign does not copy inherited properties.

This answer on a similar problem provided a working alternative:

function main (sources) {
  const vdom$ = sources.DOM.select('document').events('keydown')
    .map(ev => cloneEvent(ev))
    .map(mykey => div('Key pressed: ' + mykey.key + ', code:' + mykey.code))
    .startWith(div('Press a key.'))

  return {
    DOM: vdom$
  }
}

function cloneEvent(e) {
  if (e===undefined || e===null) return undefined;
  function ClonedEvent() {};  
  let clone=new ClonedEvent();
  for (let p in e) {
    let d=Object.getOwnPropertyDescriptor(e, p);
    if (d && (d.get || d.set)) Object.defineProperty(clone, p, d); else clone[p] = e[p];
  }
  Object.setPrototypeOf(clone, e);
  return clone;
}

See updated codepen.io example.

These SO questions and answers also helped clarify the situation:

Poor Use Case of Object.assign() - Simple Example

Javascript hasOwnProperty always false on Event objects?

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
  • Thank you for the clarification. To get around the problem, I incapsulated the event object in a new object {event: ev, type: 'keydown'}, to avoid messing around with the object's internal details. – cmant Nov 06 '18 at 18:32
  • I agree—simpler approach. – bloodyKnuckles Nov 06 '18 at 18:33