Binding event handlers javascript

The «event» binding

The event binding allows you to add an event handler for a specified event so that your chosen JavaScript function will be invoked when that event is triggered for the associated DOM element. This can be used to bind to any event, such as keypress , mouseover or mouseout .

Example

 
Mouse over me
Details

Now, moving your mouse pointer on or off of the first element will invoke methods on the view model to toggle the detailsEnabled observable. The second element reacts to changes to the value of detailsEnabled by either showing or hiding itself.

Parameters

  • Main parameter You should pass a JavaScript object in which the property names correspond to event names, and the values correspond to the function that you want to bind to the event. You can reference any JavaScript function — it doesn’t have to be a function on your view model. You can reference a function on any object by writing event < mouseover: someObject.someFunction >.
  • Additional parameters
    • None

    Note 1: Passing a “current item” as a parameter to your handler function

    When calling your handler, Knockout will supply the current model value as the first parameter. This is particularly useful if you’re rendering some UI for each item in a collection, and you need to know which item the event refers to. For example,

    Two points to note about this example:

    • If you’re inside a nested binding context, for example if you’re inside a foreach or a with block, but your handler function is on the root viewmodel or some other parent context, you’ll need to use a prefix such as $parent or $root to locate the handler function.
    • In your viewmodel, it’s often useful to declare self (or some other variable) as an alias for this . Doing so avoids any problems with this being redefined to mean something else in event handlers or Ajax request callbacks.

    Note 2: Accessing the event object, or passing more parameters

    In some scenarios, you may need to access the DOM event object associated with your event. Knockout will pass the event as the second parameter to your function, as in this example:

    Mouse over me

    If you need to pass more parameters, one way to do it is by wrapping your handler in a function literal that takes in a parameter, as in this example:

    Now, KO will pass the event to your function literal, which is then available to be passed to your handler.

    Alternatively, if you prefer to avoid the function literal in your view, you can use the bind function, which attaches specific parameter values to a function reference:

    Note 3: Allowing the default action

    By default, Knockout will prevent the event from taking any default action. For example if you use the event binding to capture the keypress event of an input tag, the browser will only call your handler function and will not add the value of the key to the input element’s value. A more common example is using the click binding, which internally uses this binding, where your handler function will be called, but the browser will not navigate to the link’s href . This is a useful default because when you use the click binding, it’s normally because you’re using the link as part of a UI that manipulates your view model, not as a regular hyperlink to another web page.

    However, if you do want to let the default action proceed, just return true from your event handler function.

    Note 4: Preventing the event from bubbling

    By default, Knockout will allow the event to continue to bubble up to any higher level event handlers. For example, if your element is handling a mouseover event and a parent of the element also handles that same event, then the event handler for both elements will be triggered. If necessary, you can prevent the event from bubbling by including an additional binding that is named youreventBubble and passing false to it, as in this example:

     

    Normally, in this case myButtonHandler would be called first, then the event would bubble up to myDivHandler . However, the mouseoverBubble binding that we added with a value of false prevents the event from making it past myButtonHandler .

    Note 5: Interaction with jQuery

    Knockout will use jQuery, if it is present, for handling UI events. To disable this behavior and instruct Knockout to always use native event handling, you can set the following option in your code before calling ko.applyBindings :

    ko.options.useOnlyNativeEvents = true; 

    Dependencies

    None, other than the core Knockout library.

    Источник

    How to handle bind an event using JavaScript?

    In this tutorial, we will learn how to handle bind an event using JavaScript.

    Events are the actions or occurrences in the system by the browser or users. There are various types of events that represent various activities performed by the browser or users. For example, if a user clicks on a button, it triggers an event named «click.» Similarly, if a webpage finished loading, it triggered an event called «load.»

    An Event Listener is a program that continuously listens to or waits for an event to occur. It is one of the most important parts of JavaScript. The functions or methods that execute after an event occurs and handle that event are called the Event Handlers.

    JavaScript binds the events to their respective event handlers to handle the events. And the method addEventListener is used for this purpose.

    Binding Event with Event Handlers using the addEventListener

    In JavaScript, the addEventListener method binds a specific event handler to a specific event. It usually takes as parameters the event name and an event handler function and binds the event to that event handler

    Syntax

    Users can follow the below syntax to handle bind an event using addEventListener in JavaScript.

    element.addEventListener(event, eventHandler, useCapture);

    In the above syntax, we have passed the event and eventHandler callback function as a parameter of the addEventListener method.

    Parameters

    • event − it is the name of the event which needs to be bound with the event handler.
    • eventHandler − a function or method that handles a particular event
    • useCapture − it is defined as whether the event handler executes in the bubbling or capturing phase. It is optional, and by default, it is false, which implies the bubbling phase.

    Example

    Bind a click event with a button

    In the below example, we have used the addEventListener to bind an event in JavaScript. We are changing an element’s inner text using a button click event.

    html> body> h2>Bind an event using i>addEventListener/i> in JavaScript/h2> button id = "btn"> Click me/button> p id = "root"> Welcome to Tutorialspoint!/p> script> // Event Handler function clickHandler() document.getElementById('root').innerHTML = 'Button is Clicked!' > let element = document.getElementById('btn') // Binding a click event element.addEventListener('click', clickHandler) /script> /body> /html>

    In the above output, users can see after clicking the button a “click” event trigger observed by Javascript Event Listener, and it is called the specified Event Handler for that event which is, in this case, the clickHandler function. The clickHandler function then changes the inner text of the root div.

    Example

    Bind multiple events with an element

    In the below example, we have used the addEventListener to bind multiple events in JavaScript. We have used the «click,» «mouseenter,» and «mouseleave» events in this example. The «mouseenter» event is triggered whenever the user moves the mouse pointer over that element. The «mouseleave» event is triggered whenever the user leaves the mouse pointer on that element. We used the event handlers to change the background color and text of that element.

    html> body> h2>Bind multiple events using i>addEventListener/i> in JavaScript/h2> div id = "element" style = "border: 1px solid black; padding: 10px;"> Welcome to Tutorialspoint! /div> script> let element = document.getElementById('element') // Event Handlers function clickHandler() element.innerHTML = 'The element is Clicked!' element.style.backgroundColor = '#ff9797' > function mouseEnterHandler() element.innerHTML = 'The Mouse pointer is on the element!' element.style.backgroundColor = '#56ea87' > function mouseLeaveHandler() element.innerHTML = 'The Mouse pointer leaves the element!' element.style.backgroundColor = '#56eade' > // Binding multiple events element.addEventListener('click', clickHandler) element.addEventListener('mouseenter', mouseEnterHandler) element.addEventListener('mouseleave', mouseLeaveHandler) /script> /body> /html>

    Removing Event Handlers from Events using the removeEventListener

    In JavaScript, removeEventListener is used to remove a specific event handler associated with an event. It takes the event, and the event handler in the parameters, and the method removes the binding between them.

    Syntax

    Users can follow the below syntax to use removeEventListener in JavaScript.

    element.removeEventListener(event, eventHandler, useCapture)

    Parameters

    • event − it is the name of the event which needs to be unbound with the event handler.
    • eventHandler − a function or method which handles the particular event.
    • useCapture − it is defined as whether the event handler executes in the bubbling or capturing phase. It is optional, and by default, it is false, which implies the bubbling phase.

    Example

    In the below example, we have used the removeEventListener to unbind an event from the associated event handler in JavaScript. We are unbinding the «mouseenter» event’s event handler from that event by a button’s «click» event handler. The «mouseenter» event handler increments a counter value, and by using the «Stop Counter» button, we are stopping the counter from incrementing anymore.

    html> body> h2>Unbinding an event from the associated event handler using i>removeEventListener/i> in JavaScript/h2> button id = "btn"> Stop Counter/button> div id = "element" style = "border: 1px solid black; padding: 10px;"> Counter: 0 /div> script> let element = document.getElementById('element') let button = document.getElementById('btn') let count = 0 // Event Handlers function mouseEnterHandler() count += 1 element.innerHTML = "Counter: " + count > function clickHandler() // unbinding mouseenter event element.removeEventListener('mouseenter', mouseEnterHandler) > // Binding events button.addEventListener('click', clickHandler) element.addEventListener('mouseenter', mouseEnterHandler) /script> /body> /html>

    Before the “Stop Counter” button, click counter is incrementing on the “mouseenter” event.

    After the “Stop Counter” button is clicked, the counter is stopped

    Источник

    Binding and unbinding of event handlers

    How to attach or detach a handler function to an event, such as click, focus, or submit.

    Modern browsers support addEventListener() and removeEventListener() for adding or removing event handlers; IE 8 has its own methods. If you need to support both, use these little helpers as a replacement to jQuery’s $.on() and $.off() methods:

    function addEvent(el, type, handler) if (el.attachEvent) el.attachEvent('on'+type, handler); else el.addEventListener(type, handler);
    >
    function removeEvent(el, type, handler) if (el.detachEvent) el.detachEvent('on'+type, handler); else el.removeEventListener(type, handler);
    >
    var el = document.querySelector('textarea');

    // attach anonymous function to click event
    addEvent(el, 'click', function()< console.log('Clicked!'); >)

    // attach a named function
    var foo = function()< console.log('Focused!'); >;
    addEvent(el, 'click', foo);

    // remove a previously attached function
    removeEvent(el, 'click', foo);

    Anonymous functions used as event handler cannot be unbound. A reference to the function used for binding the event must be passed to removeEvent() .

    It’s not required to unbind event handlers when removing DOM elements. JavaScript’s garbage collection will take care of it and free up the reserved memory.

    w3schools offers a useful list of available HTML DOM events. These are HTML attribute names; when binding/unbinding events with the above given helper function, omit the «on» prefix of the name to get the event type. For example, use «mouseup» instead of «onmouseup».

    Alternatively, you can also set the event attribute of an element directly. But it’s only possible to assign one handler per element:

    var el = document.querySelector('textarea');

    // set callback
    el.onblur = function()< console.log('Blurred textarea'); >;

    // remove callback
    delete el.onblur;

    // assign handler to window object
    window.onload = function()< alert('Window has loaded.'); >;

    Use the «on» prefix for setting and removing properties such as onblur or onclick of elements.

    Read up on how to live bind events in vanilla JavaScript.

    Источник

    Читайте также:  Java org apache kafka
Оцените статью