Приглашаем посетить
Тургенев (turgenev-lit.ru)

Special Event Considerations

Special Event Considerations

Using JavaScript function pointers, you can assign an event handler in one frame or a browser to an event property in another. This powerful technique allows easy sharing of code between documents; however, it also adds complexity.

The event object is tightly related to the window that fired the event. Therefore, even though an event handler might be located in a document in another frame, the event object of the frame that generated the event must be used, which requires walking the object hierarchy from the element that generated the event to the event object.

While this technique allows you to write flexible and powerful code, it is limited by the security model in the browser. For example, a page cannot assign event handlers to the events of a frame or browser window that contains a document from another domain. Without this restriction, a rogue page could hook the keyboard events and track the entry of confidential information. Furthermore, once the user navigates away from a page, all the event handlers are detached. This is consistent with the Dynamic HTML object model, in which a new page is always provided with an entirely fresh state.

The function assignment method is the most efficient way to hook events in another frame; it does not require the creation of an extra function handler. However, this technique allows access only to the element generating the event:

<SCRIPT LANGUAGE="JavaScript">
   function doClick() {
      /* This is the event handler for the click event of the
         document in window2. */
      /* The event object cannot be accessed directly using
         the current window's event object. Instead,
         window2's event object must be accessed. 
         The this pointer passed in points to the document
         that generated the event. */
      with (this.document.parentWindow.event) {
         // Use the event object.
      }
   }

   var window2 = window.open("sample.htm");
   /* Bind the event handler of window2 to the
      doClick function in this document. */
   window2.body.onclick = doClick;
</SCRIPT>

Scripting events across frames is the basis of the Event Tutor example in Chapter 3, "Dynamic HTML Event Model." The Event Tutor works by dynamically hooking the events of the sample document and outputting strings in the current window.

[Содержание]