What does event binding mean?

2019-03-24 16:33发布

What does event binding mean? I always come across this word whenever I search around the internet and whatever I try to look for the meaning, it's still vague to me @_@ A while ago, while reading some blogs regarding JavaScript I see people using this sacred word that I cannot grasp.

4条回答
乱世女痞
2楼-- · 2019-03-24 17:16

Event binding refers to telling the browser that a particular function should be called whenever some 'event' occurs. Events mostly relate to user input, such as clicks.

An example of binding to an event in jQuery can be the following:

$("#elem").bind("click", function() {
    alert("Clicked!");
});

This binds a function to click event of DOM object with identifier elem. When user clicks it, an alert (message box) will be shown. Binding is done by invoking the jQuery bind function but there are other means to do that, (e.g. jQuery click function in case of binding to click event).

查看更多
唯我独甜
3楼-- · 2019-03-24 17:17

When you bind something to an event, it will be triggered when the event is fired. It's like gluing a fog horn to the brake pedal on your car.

查看更多
时光不老,我们不散
4楼-- · 2019-03-24 17:23

When you perform an action on a web page it will trigger an event. This might be something like:

  • Click a button
  • Select a value from a drop down
  • Hover the mouse over an item

These events can be captured in your JavaScript code.

A common (and often miguided) way of caturing events is to do so on the HTML element itself (as shown in the onclick attribute below)

<input id="MyButton" type="button" value="clickme" onlick="Somefunction()" />

So, when the user clicks the button, the SomeFunction function will be executed.

However, it is considered a better approach to adopt a technique called 'late-binding'. This ensures that your HTML and JavaScript are kept completely separate.

So, we can modify the above exmample like so:

document.getElementById("MyButton").onclick = function(){
   //functionality here
}

jQuery makes this even easier:

$("#MyButton").click(function(){
    //functionality here
});
查看更多
看我几分像从前
5楼-- · 2019-03-24 17:30

Binding in JS, is to capture some events (like focus, click, onmouseover, etc) and perform some other stuff before the actual process starts.

Detailed explanation:

http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/

http://api.jquery.com/bind/

查看更多
登录 后发表回答