ten1seven / what-input

A global utility for tracking the current input method (mouse/pointer, keyboard or touch).
https://ten1seven.github.io/what-input
MIT License
1.35k stars 89 forks source link

Emit events when input or intent changes #59

Closed mihkeleidast closed 7 years ago

mihkeleidast commented 7 years ago

I have the following use case: tooltips that open on click with touch, on focus with keyboard and on hover with mouse. In order to do that, I have to bind a listener on the corresponding event. Now, when the input (or intent) changes, I need to unbind the previous listener and bind the correct one.

As of now, I have a MutationObserver listening to changes on the html element, but I think it could be a lot simpler if this library could emit an event when the input (and/or intent) changes.

ten1seven commented 7 years ago

Great idea! I'll get working on it.

ten1seven commented 7 years ago

Hi @risker, just added this into the current version and deployed today. I looked into custom events, but that had too many backward compatibility risks, so I went with this.

Take a look and let me know what you think!

// create a function to be fired
var myFunction = function(type) {
  console.log(type)
};

// fire `myFunction` when the intent changes
whatInput.onChange(myFunction, 'intent');

// fire `myFunction` when the input changes
whatInput.onChange(myFunction, 'input');
mihkeleidast commented 7 years ago

Hey, got around to switching my observer for this. Adding the functions works like a charm. But there should also be a way to unbind the functions. For example, when destroying the instance of the tooltip plugin, it is no longer necessary to run the callback. It actually breaks the plugin by running an internal function after the instance has been destroyed.

ten1seven commented 7 years ago

Ah, yep, good call! I'll get working on that.

ten1seven commented 7 years ago

Okay, just made an update. You should now use whatInput.registerOnChange(myFunction) and can remove it with whatInput.unRegisterOnChange(myFunction). I released this as v4.3.0.

mihkeleidast commented 7 years ago

Thanks, this works as expected.