`

javascript - trigger event and custom events

阅读更多

In the previous post - javascript - trick to handlers management we dicussed the handlers management and the important functions such as addEvent, removeEvent and the last triggerEvent which provides  a cross-browser implementation of event management.

 

 

Let's see again the code of triggerEvent.

 

 

function triggerEvent(elem, event) {

  var handler = getData(elem).handler, parent = elem.parentNode || elem.ownerDocument;
  if (typeof event === 'string') {
    event = { type: event, target: elem };
  }

  if (handler) {
    handler.call(elem, event);
  }
  // Bubble the event up the tree to the document,
  // Unless it's been explicitly stopped
  if (parent && !event.isPropagationStopped()) { // NOTE in Chrome, e.g. for event 'udpate' which are passed in as a string, then it does not have the isPropagationStopped properties.
    triggerEvent(parent, event);
  // We're at the top document so trigger the default action
  } else if (!parent && !event.isDefaultPrevented()) {
    var targetData = getData(event.target), targetHandler = targetData.handler;
    // so if there is handler to the defalt handler , we execute it 
    if (event.target[event.type]) {  // I Suppose that it is the event.type rather than just the type
      // Temporarily disable the bound handler, 
      // don't want to execute it twice
      if (targetHandler) {
        targetData.handler = function () { };
      }
      // Trigger the native event (click, focus, blur)
      event.target[event.type](); // I suppose that it is the event.type rather than the type 

      // restore the handler
      if (targetHandler) {
        targetData.handler = targetHandler;
      }
    }
  }
}
 

 

Normally events occurs whe a user triggers them (such as clicking or moving the mouse). however, they are many cases where it's appropriate to simulate a native event occurring....

 

 

With all the work of integrating cross-browser events. Thus far, supporting custom events ends up being relatively simple. Custom event are a way of simulating the experience (to the end user) of a real event without having to use the browser's underlying event structure. custom events can be an effective means of indirectly communicating actions to elements in a one-to-many way.

 

Below shows an example of a custom events across a number of elements.

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!-- 
    @name : customeventsdemo.js
    @comment: custom events are a way of simulating the experience (to the end user) of a real event without having to use the browser's underlying event structure
    with the code that we've written for addEvent, removeEvent , and triggerEvent - nothing else has to change in order to support custom events.  Functionally there is no difference 
    between an event that does exist and will be fired by the browser and an event that does not exit and will only fire when triggered manually. You can see an example of triggering a custom event in below  
    -->
    <title></title>
    <script type="text/javascript" src="addremoveevents.js"></script>
    <script type="text/javascript">
      addEvent(window, "load", function () {
        var li = document.getElementsByTagName("li");
        for (var i = 0; i < li.length; i++) {
          addEvent(li[i], "update", function () { // update event is not some events that exists in the browser for the li element
            this.innerHTML = parseInt(this.innerHTML) + 1;
          });
        }

        var input = document.getElementsByTagName("input")[0];
        addEvent(input, "click", function () {
          var li = document.getElementsByTagName("li");
          for (var i = 0; i < li.length; i++) {
            triggerEvent(li[i], "update");  // with the trigger event you can fire the event manualy, though you may not fire thevent automatically when you click some element
          }
        });
      });
     
    </script>
</head>
<body>

<input type="button" value="Add 1" />
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
</body>
</html>
 

 

 

you may notice the comment that I inserted like this: 

 

 

 

// NOTE in Chrome, e.g. for event 'udpate' which are passed in as a string, then it does not have the isPropagationStopped properties.

 

 

this is to say that it is supported to pass a string to signify the event. 

 

 

triggerEvent(li[i], "update");

 

 

in the above code, you see that you are passing the string 'update' as the event, you can pass the real event object (or a fixed event object), by the event object, you can expect that the isPropagationStopped return true or false. 

分享到:
评论

相关推荐

    Microsoft SharePoint 2010 Developer Reference

    - **Workflow Event Receivers:** Special event receivers that trigger based on workflow events. - **Workflow Services:** Services that can be used to interact with workflows programmatically. - **...

    深入解析JavaScript框架Backbone.js中的事件机制

    model.trigger('custom_event'); ``` 在Backbone中,事件是通过一个名为`_events`的内部数组来存储和管理的。当使用`listenTo`方法时,监听者会将事件名和对应的回调函数添加到被监听对象的`_events`数组中。触发...

    JQuery事件Demo

    console.log('Custom event triggered!'); }); // 触发自定义事件 $(document).trigger('myCustomEvent'); ``` ### 五、事件解除绑定 使用`.off()`方法可以解除事件绑定,以避免内存泄漏或重复处理。例如,解除...

    详解JavaScript中的自定义大事编写_.docx

    在JavaScript中,自定义事件(Custom Events)是一种增强网页交互性和灵活性的重要机制。它们允许开发者在不依赖特定DOM操作或用户交互的情况下,触发和响应特定的事件。这在模块化编程、组件化开发以及实现复杂逻辑...

    最近版本jquery3.1.1

    - **事件触发(Triggering Events)**:可以手动触发事件,如`$("#element").trigger("click")`。 #### 3.3 动画效果 - **动画(Animation)**:`slideUp()`, `slideDown()`, `fadeIn()`, `fadeOut()`等方法提供了...

    jQuery弹出层

    - **自定义主题(Custom Themes)**: 允许用户根据品牌风格调整弹出层外观。 - **插件集成(Plugin Integration)**: 结合其他jQuery插件,如日期选择器、表单验证等。 - **性能优化(Performance Optimization)**:...

    jquery初学者程序包,

    - **事件触发(Triggering Events)**:`.trigger()`方法可触发已绑定的事件,如`$("#element").trigger("mouseover")`。 - **事件代理(Event Delegation)**:使用`.on()`的事件委托功能,可以处理动态添加的...

    python3.6.5参考手册 chm

    The json module: JavaScript Object Notation The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific ...

    jquery学习笔记

    - **自定义事件(Custom Events)**: 可以使用`.trigger()`和`.on()`来创建和监听自定义事件。 ### 5. jQuery UI jQuery UI是jQuery的扩展库,提供了丰富的用户界面组件,如日期选择器、对话框、拖放功能等。在...

    jquery1.7 中文文档

    - **触发事件(Triggering Events)**: 使用 `trigger()` 方法可手动触发事件,如 `$elem.trigger('customEvent')`。 ### 3. 动画效果(Animation) - **淡入淡出(Fade)**: `fadeIn()`, `fadeOut()` 和 `...

    dime:Uber-micro库(&lt;1kb),用于选择元素和处理自定义事件。 没有依赖关系。 IE9 +

    dime.js 方法 元素= $('selector') 元素= $('selector')[0] 元素|元素.on() 元素|元素.trigger() 元素.each() 元素.find() 用法 // Select multiple elements ...// Trigger a custom event on elements.

    30个jquery经典Demo

    27. **自定义事件(Custom Events)**:通过`.trigger()`和`.on()`创建并触发自定义事件,增加代码灵活性。 28. **DOM操作(DOM Manipulation)**:`.append()`, `.prepend()`, `.remove()`等方法用于DOM结构的增...

    JQuery_1.4_API.CHM JQuery_1.4_API.CHM

    3. **触发事件(Triggering Events)**:使用`trigger()`方法可以手动触发已绑定的事件。 三、动画效果(Effects) 1. **基本动画(Basic Effects)**:如`fadeIn()`, `fadeOut()`, `slideToggle()`等,用于元素的...

    jqueryAPI

    5. **事件触发(Event Triggering)**:`trigger()`方法可以手动触发事件,如`$("#element").trigger("mouseenter");`模拟鼠标进入元素。 6. **事件委托(Event Delegation)**:使用`.on()`的事件委托模式,可以在...

    jquery帮助文档,很好用

    2. **事件触发(Triggering Events)**:使用`trigger()`方法可手动触发事件,`$("#element").trigger("mouseover")`模拟鼠标悬停事件。 三、jQuery动画效果 1. **基本动画(Basic Animations)**:`fadeIn()`, `...

    50 个 jquery例子

    17. **自定义事件(Custom Events)**:可以使用 `.trigger()` 和 `.on()` 创建并触发自定义事件。 18. **效果(Effects)**:jQuery 还包含淡入淡出(`.fadeIn()`, `.fadeOut()`)、滑动(`.slideToggle()`)等...

Global site tag (gtag.js) - Google Analytics