DEV Community

Cover image for How to handle anything
Matt Ellen-Tsivintzeli
Matt Ellen-Tsivintzeli

Posted on

2

How to handle anything

This is just a small change. Initially I created functionality to allow for click events to be handled, like so:

if(el.getAttribute('onclick'))
{
  let onclick = el.getAttribute('onclick');
  el.setAttribute('onclick', '');
  if(onclick in _internal.originalViewmodel.functions)
  {
    el.addEventListener('click', _internal.originalViewmodel.functions[onclick].bind(_internal));
   }
}
Enter fullscreen mode Exit fullscreen mode

Obviously people will want to handle any element event, so I need to expand handling to allow for that.

My chosen method is a little brittle. I assume an attribute that starts on is and event, and assign accordingly.

for(let attr of el.attributes)
{
  if(attr.name.startsWith('on'))
  {
    let eventName = attr.name.substring(2);
    let eventHandlerName = attr.value;
    if(eventHandlerName in _internal.originalViewmodel.functions)
    {
      el.setAttribute(attr.name, '');
      el.addEventListener(eventName, _internal.originalViewmodel.functions[eventHandlerName].bind(_internal));
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

So now this is possible:

<div id="app">
  <input type="text" onkeyup="annoy">
</div>
Enter fullscreen mode Exit fullscreen mode
import {rjsf} from '../rjsf.js'

(function()
{
  const appElement = document.getElementById('app');

  const app = new rjsf(appElement);

  const viewmodel = 
        {
          functions:
          {
            annoy: function(e)
            {
              e.preventDefault();
              alert('this is annoying isn\'t it?');
            }
          },
        };

  app.init(viewmodel);

})();
Enter fullscreen mode Exit fullscreen mode

Which will alert a message every time there is a keyup event in the input box.

Next time will be a longer article investigating how to make a for element.

Please let me know any thoughts or questions you have in the comments below.

❤️, share, and follow for the next instalment!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more