Analysis of Bind of event usage in JQuery

  • 2020-06-07 03:56:52
  • OfStack

This article analyzes the Bind() event usage in JQuery. Share to everybody for everybody reference. The specific analysis is as follows:

Let's first look at the definition of 1:


.bind( eventType [, eventData], handler(eventObject))

The main function of the.Bind () method is to provide the behavior of some event methods on the object to which it is bound. The meanings of the three parameters are as follows:

eventType is a string type event type, which is what you need to bind to. This type may include the following: blur, focus, focusin, focusout, load, scroll, scroll, click, dblclick, mousedown, mouseup, mousemove, mouseout, change, select, submit, keydown, keyup, error. It should be noted that the event methods used in javascript are not those in JQuery. The event methods in JQuery are all one "on" before JavaScript, such as onclick,onblur and so on.

The eventData parameter is an optional parameter, although it is used less often. If this parameter is provided, then we can pass 1 additional information to the event handler. This parameter has a good use in dealing with closures. I'll give you an example of that in a second.

Handler is the number of processes to bind to, which is essentially the callback function, after processing the data.

1. The first simple bind () event -Hello Word


<input id="BtnFirst"type="button"value="Click Me"/>
<script>
$(function () {
 $("#BtnFirst").bind("click",function(){
  alert("Hello World");
 });
})
</script>

After opening the page, click the button "Click Me" and "Hello World" will pop up. This is our simplest binding event. That's easy.

2. Bind multiple events

You can bind multiple events via bind() (in fact, this is known as chain programming in JQuery and Linq). The main function of the implementation is that when we click, "Hello World" pops up, and when we leave button, 1 div appears.


<div>
<input id="BtnFirst"type="button"value="Click Me"/></div>
<div id="TestDiv"style=" width:200px; height:200px; display:none; ">
</div>
<script>
$(function () {
 $("#BtnFirst").bind("click", function () {
  alert("Hello World");
 }).bind("mouseout", function () {
  $("#TestDiv").show("slow");
 });
})
</script>

This code page is easy to understand, that when button is clicked, a "Hello World" pops up and displays div when it leaves. For JQuery animations, you can use "slow", "fast" and "normal", but you can also set the relevant number of milliseconds.

3. Object of the bind() event

The callback function Handler can take one argument, and when the function is called, an JavaScript event object is passed in as one argument.

This event object is usually an unnecessary parameter that can be omitted, because when the event handler is bound it knows exactly what it should do when it is triggered, and it is usually sufficiently informed. In some cases, however, more information about the user environment needs to be obtained during event initialization.

Here's an example from JQuery.com:


<style> 
 p {background:yellow;font-weight:bold;cursor:pointer;3 padding:5px;}
 p.over {background:#ccc;}
 span {color:red;}
</style>
<p>Click or double click here.</p>
<span></span>
<script>
 $("p").bind("click", function(event){
  var str = "( " + event.pageX + ", " + event.pageY + " )";
  $("span").text("Click happened! " + str);
 });
 $("p").bind("dblclick", function(){
  $("span").text("Double-click happened in " + this.nodeName);
 });
 $("p").bind("mouseenter mouseleave", function(event){
  $(this).toggleClass("over");
 });
</script>

The main function here is to display the current coordinates relative to the page in the span tag when the user clicks on the p object, which USES the event event. Pass in the parameters.

4. unbind () event

unbind([type],[data], Handler) is the reverse of bind(), which removes the binding event from each matching element. If there are no parameters, all bound events are removed. You can unbind custom events that you registered with bind(). If an event type is provided as a parameter, only bound events of that type are removed. If you take the handler passed at binding time as the second argument, only this particular event handler will be removed.


<body onclick="MyBodyClick()">
 <div onclick="MyClickOut()">
  <div onclick="MyClickInner()">
   <span id="MySpan">I love JQuery!! </span>
  </div>
 </div>
 <span id="LooseFocus"> Lose focus </span>
</body>
<script>
function MyClickOut() {
 alert("outer Div");
}
function MyClickInner() {
 alert("Inner Div");
}
function MyBodyClick() {
 alert("Body Click");
}
var foo = function () {
 alert("I'm span.");
}
$(function () {
 $("#MySpan").bind("click", foo);
})  
$(function () {
 $("#LooseFocus").unbind("click", foo);
})
</script>

The above code is also easy to understand: when the user's mouse hovers over span, it cancels the click event of span. So, in the end it just pops out alert from body.

Finally, take a quick look at the use of one() events. In fact, one and bind are the same, both generated for binding events. One is basically the same as bind, except that when you call ES127en.event.add, you make a small adjustment to the registered event handling function. One calls jQuery.event.proxy to handle the incoming agent. When the event triggers the function that calls the proxy, the event is removed from cache before the registered event function is executed. Here is the application of closures to get a reference to the event function registered by fn.

Rules of Use:


one(type,[data],fn)

Bind a one-degree event handler to a specific event (like click) for each matching element. The event handler is executed only once per object. The other rules are the same as the bind() function. This event handler receives an event object that prevents the default behavior. If you want to both cancel the default behavior and prevent event bubbling, the event handler must return false.

Post 1, bind and one's respective code implementation, you can do a little comparison:

Implementation of Bind() code:


bind : function(type, data, fn) { 
 return type == "unload" ? this.one(type,data,fn) : this.each(function(){
 //fn || data, fn && data To achieve the data Parameters are optional  
  jQuery.event.add(this, type, fn || data, fn && data); 
 }); 
}

One() code implementation:


one : function(type, data, fn) { 
 var one = jQuery.event.proxy(fn || data, function(event) { 
  jQuery(this).unbind(event, one); 
  return (fn || data).apply(this, arguments);
 //this-> Current element  
 }); 
 return this.each(function() { 
  jQuery.event.add(this, type, one, fn && data); 
 }); 
}

5. Finally, I want to post a bubble event, because when dealing with binding events, if the call to the internal event may trigger an event outside, so give everyone a reference.

Here you can refer to the following javascript event bubble article: Introduction and Application of JavaScript Event Bubble.

In short, what is a bubble event? In fact, the simplest way to think about it is event propagation, which broadcasts from the internal controls to the elements of the parent class, then 1 straight up to the ancestor level elements.

Then bubble instance code:


<body onclick="MyBodyClick()">
 <div onclick="MyClickOut()">
  <div onclick="MyClickInner()">
    <span id="MySpan">
     I love JQuery!!
    </span>
  </div>
 </div>
</body>
<script type="text/javascript">
 function MyClickOut() {
  alert("outer Div");
 }
 function MyClickInner() {
  alert("Inner Div");
 }
 function MyBodyClick() {    
  alert("Body Click");
 }
 $(function () {
  $("#MySpan").bind("click", function (event) {
   alert("I'm span");
   event.stopPropagation();
 });
</script>

I hope this article has been helpful for your jQuery programming.


Related articles: