Onclick event does not fire the first time a button is clicked in Mithril

Why is the click callback not called the first time after entering some text in the input, for example, in this script?

var app = {}; app.controller = function(){ this.data = m.prop(""); this.click = function(){ alert("button clicked"); }; }; app.view = function(ctrl){ return m("html", [ m("body", [ m("div", [ m("p", ctrl.data()), m("input[type=text]", { onchange: m.withAttr("value", ctrl.data) }), m("button", { onclick: ctrl.click }, "Click") ]) ]) ]); }; m.module(document, app); 
+6
source share
1 answer

The onchange event in the event is fired with the mouse down, which causes the view to be redrawn, which causes the button to move down. The click event is fired when the mouse is clicked (try to press and hold the mouse button without typing anything to understand what I mean). Usually a quick click has a space of ~ 200 ms between the basic onmousedown and the onmouseup events due to the physical distance between the rest and the pressed position on the mechanical switch of the mouse button.

So basically what happens:

1 - mouse button is pressed, onchange starts

2 - view redraws and moves the button down to make room for text in <p>

3 - after a while, the mouse button is not pressed, launching onclick

4 - the event looks at the current position of the mouse (now it is on top of the <p> ), so it does not cause an event on the button

You can see that this is so by typing something, then clicking and holding the mouse button and then dragging the cursor over the button again.

To avoid this problem, you can use onmousedown instead of onclick so that both onchange and onmousedown happen in the same animation frame or if the user interface allows, you can move the <p> under the button.

+9
source

Source: https://habr.com/ru/post/975286/


All Articles