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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more