Event binding __java in Javascript

Source: Internet
Author: User
Tags anonymous

Providing an event-handling portal for a component can greatly improve the closure of the component while making the component very well communicated to the outside world. And this is one of the development patterns that we've been used to,. NET, DHTML, and so on, all provide a complete set of event-handling models. The following is a summary of the use of events in DHTML.


DHTML provides a way to use 3 of events, respectively:

1, Inline HTML: <element onxxx= ' handler ' ></ELEMENT>

This is the simplest and most commonly used method of event binding, but the OnXxx value here is handler is not quite certain. In fact, this handler position can place any legitimate JavaScript statements, because IE builds the DHMTL tree with an ' anonymous ' member method for the current element, onxxx the handler that points to the method. For example, we write, <element id= ' elmt ' onxxx= ' var abc = 0; for (Var i=0 i < i++) abc+=i; ></element> In fact, the following code structure exists in the DHMTL tree species:
function Anonymous ()
{
    var abc =0; for (var i=0 i < i++) abc+=i;
}

This is the ELMT object in the anonymous method.


2, Event Property:object.onXXX = Handler

The use of this method is to assign the function name (handler) to the element's predefined event properties (OnXXX). Here are two questions to note:

One is that we are using OBJECT.ONXXX = handler to ensure that object is already generated in the page. For example, we give the event handler function for Document.body, we must ensure that document.body already exists, that is, we cannot use document.body in the global statement before <body>;

Second, handler must be a function name, and it can be different from any JavaScript statement using the handler in Method 1. Our most error-prone use is when we are accustomed to using <element id= ' elmt ' OnXXX = ' return false ' ></element> in inline HTML if this is used elmt.onxxx= ' return false; '. Then the rest of the dishes, there will be no effect, of course, ie also does not complain. The correct use is:
Elmt.onxxx = function () {return false;}


3. Named Script: <script for = object EVENT = onclick>

IE exclusive support, not how to use, do not feel any special place ha. If you know the beauty of it, let it be heard.

The DOM provides two kinds of event-handling uses, namely:

1, attachevent Method:
How to use: bsuccess = Object.attachevent (sevent, fpnotify). The explanation is copy MSDN.
Parameters
Sevent Required. String that specifies any of the standard DHTML Events.
Fpnotify Required. Pointer that specifies the function to call when sevent fires.
Return Value
Boolean. Returns one of the following possible values:true the function is bound successfully to the event.
False the function is not bound to the event.
The way DOM provides this event is actually a collection operation, and we can attach multiple event handlers on the same event signature multiple times, such as:
Window.attachevent (' onload ', handler1);
Window.attachevent (' onload ', handler2);
Window.attachevent (' onload ', handler3);
Window.attachevent (' onload ', handlern);

This n handler will be executed, but the order of execution is not guaranteed. Here is an exception, attachevent on Document.body attach event ' onload ' has no effect, but the ' onload ' of Attch window object is correct. Depending on the order in which the page is initialized, and document.body.attachEvent (' onload ', handler) returns True, this is due to a bug in IE.

Note the difference between the event property of DHTML and the way Dom Attachevent:

event property Way, when the event is triggered, the incident handler function is a parameterless function, and we can only read the event-related information through the properties of the window of the event. Attachevent method, when the event handler function is triggered, the first parameter of the function Arguments[0], and the default is the event on that window. What does that mean.   No, see here. Part of the---------------------------------------------supplements----------------------------------------------------- A reference to a JavaScript object
To reduce the number of times a JavaScript object downloads, Tasian downloads javascript files only the first time the browser requests an application. A JavaScript object resides only in the top level form, and any other form needs to refer to the JavaScript object, simply by referencing it in the following ways:

The form button that needs to be referenced = top. Button//See Mscrrouter.js

While the button's truly defined JavaScript file is in the top form, the Tasian uses the following format for object definition in order to ensure that the defined object format works across browsers:
Define Object Name
function Mscrbutton ()
{
};
Ways to define Objects
Mscrbutton.onclick = function (Strwin, strName)
{
Mscrsystem.setaction (Strwin, StrName, "click", "");
};

Note that there is a semicolon at the back of each function, which is very important for Tasian. Because the JavaScript files used in Tasian are compressed, the global JavaScript object definition is synthesized into a JavaScript file. The benefit is to reduce network traffic, reduce the use of JavaScript objects for client resources, and reduce the sending of server requests.

2. Mask Application
A mask is the placement of a new object on an object, which is the mask layer. It intercepts the events of all masked objects.

Tasian all forms are in an iframe, for the form drag, in IE can easily do event capture processing, in non-IE browser, when the mouse moved to the IFRAME, the IFRAME will first handle the event, so that the drag on the IFRAME is invalid. So Tasian will add a masking layer div element that can be turned off on the IFRAME, which will open when you drag the form object, and the layer will close when the drag is complete.

3. Modal form Tasian has a special form that can operate on other forms only when it is closed. The form is called modal form. When JavaScript implements a mock form, it also uses a DIV layer, which is always at the next level of the modal form, so that it intercepts all action events on its parent form.

4. Dynamic Event Binding
In IE in dynamic event binding is implemented through attachevent, while in the Mozilla series it is used AddEventListener. Here's how the code is extracted from Document.js
if (Top.isie)
{
Odb.setcapture ();
Odb.attachevent ("OnMouseMove", __resizingme);
Odb.attachevent ("onmouseup", __endresizeme);
}
Else
{
Document.captureevents (Event.mouseevent | Event.mouseup);
Document.addeventlistener ("MouseMove", __resizingme, false);
Document.addeventlistener ("MouseUp", __endresizeme, false);
}

....
if (Top.isie)
{
Odb.detachevent ("OnMouseMove", __resizingme);
Odb.detachevent ("onmouseup", __endresizeme);
Odb.releasecapture ();

}
Else
{
Document.releaseevents (Event.mousemove | Event.mouseup);
Document.removeeventlistener ("MouseMove", __resizingme, false);
Document.removeeventlistener ("MouseUp", __endresizeme, false);
}

5. Style Object
The style object of the HTML element in IE is so powerful that everyone knows it, but the HTML style object in Mozilla has so little to recommend that it is unfamiliar to them. In fact, Mozilla's style is still very strong, ie can complete the function, it can be completed, but we do not understand it. For example, the Filter property in IE is used to set the asymptotic color, while Mozilla can be implemented with Alpha.

The following code is excerpted from Mscrsystem.js
if (!isie)
{

OEnMsk.style.filter = "alpha (opacity = 35)";
OEnMsk.style.MozOpacity = 0.35;

}
Else
{
var strhtml = "
strHTML = ">";

OObj.parentNode.insertAdjacentHTML ("BeforeEnd", strhtml);
}

Of course, Mozilla's style attribute is much more than that, it can also set the appearance of Div: round, and so the circle. -----------------------------------------------------------------the added part----------------------------------- Under IE and Firefox, the JavaScript event binding method is different, the following is the difference of two browsing, with the mouse click event as an example:

In IE, the event is onclick, binding time for Obj.attachevent ("EventName", functionname, usecapture); In this case, EventName is click, FunctionName for the event-handling method to invoke, such as a (). Usecapture indicates whether the event-handling pattern uses a capture pattern, that is, an extrovert pattern. Then the whole statement should be obj.attachevent ("onclick", A, false);
Under Firefox, the event is click, the binding time is Obj.addeventlistener ("EventName", functionname, usecapture); the corresponding statement is Obj.addeventlistener (" Click ", functionname, Usecapture);
When applied, for compatibility, you can use the following judgments to bind events:

if (window.attachevent)
{Event binding under//window}
Event bindings under Else{//firefox} _-------------------------------------------------------- J Final Supplement---------------------------------------

Today, I leave prototype1.3.1 to share my experience of Javscript event design. The technical basis of its realization lies in the essence of function, which is described in detail in the preceding two articles.

JavaScript built-in objects have event functions, such as button on the onclick event, input has onchange events. So how do we implement events in our custom classes? Very simple:
var myClass = Class. Create ();
MyClass. Prototype ={
Show:function () {
Statement

OnShow ();
},
Onshow:function () {}
}

This code actually implements the OnShow event, which is triggered when the MyClass instance show, and you can bind a function to OnShow to use the event function. In JavaScript, the built-in object event usage is the same, and its internal implementation should also be based on this pattern. However, there are two outstanding problems with this implementation:
1. Only one callback function can be bound. If you want to implement multiple bindings, you must write a lot of code yourself to encapsulate the function that you want to callback into a function.
2. Cannot pass parameters. Because OnShow can only be assigned to the function name, that is, the function body itself, and can not pass the parameters in, in order to pass the parameters, I have written a: "With the shell packaging method to the JavaScript trigger pass parameters", visible, also need to write a lot of code.

So, how can these problems be solved? Event usage for JavaScript built-in objects Let's take a moment to consider how to avoid the two problems in the class that you are implementing. Before implementing, consider the following question, perhaps to help you understand the meaning of this functionality:

My page needs to be initialized with JavaScript, but initialization must be done after the page is loaded. Usually we put the code at the bottom of the HTML file. But at this point, before the page load completes, the button clicks on the page need to call the method that must be initialized, if not make the judgment, then the script error is very easy to appear. Because it has not yet been initialized, a simple idea is to use a bool variable loaded to judge, the initial is false, after initialization is true, then click on the button hit false on the simple return. This implementation is simple, but it may cause users to find the click is invalid, and do not know why. So the perfect approach should be to capture this method, bind it to the page load completion event, and call it automatically when the page load completes.

OK, now look at the implementation code for the event design pattern:
var  myClass = Class. Create ();
MyClass. prototype ={
  initialize:function () {
   this. initevent = new  Object ();
 },
  init:function () {
  //initialization of statements to execute
  
  // The following is a callback function called Binding
   for (var  p  in  this. initevent) {
   //extend is a built-in method and cannot be As the callback keyword
    if (p = = "Extend") continue;
    this. initevent [P]. Apply (_object, []);
  }
 },
  attachoninit:function (_key, _object, _method, _arguments) {
   this. Initev ent [_key]= createfunction (_object, _method, _arguments);
 },


function  createfunction (_object, _method, _arguments) {
  return  F Unction () {
   _method. Apply (_object, _arguments);
 }
}

This code implements a class MyClass, has the Init method, triggers the OnInit event, when uses wants to bind an event, may invoke the Attachoninit method, the parameter meaning is: _key, the callback parameter function's unique identification, if repeats, the latter overwrites the former; _ Object callback function, if it is a function directly in script, you can pass the this pointer in, that is, the document object; _method, the function to callback, note that this is a function name, not a string; _arguments, an array of arguments for the callback function. There is also a function is createfunction, the role is to wrap a function, so that its built-in parameters, this is the shell packaging method of the article a common implementation. If you have seen the first two articles of the AJAX Tour series, it should be easy to understand the code above, and if there are any questions, please comment.

Use examples:
function MyFunc (s) {
alert (s);
}
var myobj = new MyClass ();
MyClass. Attach ("Key1", this, MyFunc, [123]);
MyClass. Init ();


This binds the MyFunc function to the myobj init function, which pops up the dialog box 123

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.