当前位置:Gxlcms > PHP教程 > javascript-这两种自定义事件的绑定方式有什么区别?哪种好?

javascript-这两种自定义事件的绑定方式有什么区别?哪种好?

时间:2021-07-01 10:21:17 帮助过:20人阅读

第一种方式,直接将自定义事件存放在__onfireEvents中

  1. <code>var __onfireEvents = {};
  2. function _bind(eventName, callback, is_one, context) {
  3. if (typeof eventName !== string_str || typeof callback !== function_str) {
  4. throw new Error('args: '+string_str+', '+function_str+'');
  5. }
  6. if (! hasOwnKey(__onfireEvents, eventName)) {
  7. __onfireEvents[eventName] = {};
  8. }
  9. __onfireEvents[eventName][++__cnt] = [callback, is_one, context];
  10. return [eventName, __cnt];
  11. }
  12. function on(eventName, callback, context) {
  13. return _bind(eventName, callback, 0, context);
  14. }
  15. </code>

第二种方式,同样是将自定义事件存储起来,不同之处是绑定在元素上,是否有必要?这里有什么优势吗?

  1. <code>$customSubMap = {};
  2. subscribeEvent = function ( $collection, event_name, fn ) {
  3. $collection.on( event_name, fn );
  4. if ( ! $customSubMap[ event_name ] ) {
  5. $customSubMap[ event_name ] = $collection;
  6. }
  7. else {
  8. $customSubMap[ event_name ]
  9. = $customSubMap[ event_name ].add( $collection );
  10. }
  11. };</code>

回复内容:

第一种方式,直接将自定义事件存放在__onfireEvents中

  1. <code>var __onfireEvents = {};
  2. function _bind(eventName, callback, is_one, context) {
  3. if (typeof eventName !== string_str || typeof callback !== function_str) {
  4. throw new Error('args: '+string_str+', '+function_str+'');
  5. }
  6. if (! hasOwnKey(__onfireEvents, eventName)) {
  7. __onfireEvents[eventName] = {};
  8. }
  9. __onfireEvents[eventName][++__cnt] = [callback, is_one, context];
  10. return [eventName, __cnt];
  11. }
  12. function on(eventName, callback, context) {
  13. return _bind(eventName, callback, 0, context);
  14. }
  15. </code>

第二种方式,同样是将自定义事件存储起来,不同之处是绑定在元素上,是否有必要?这里有什么优势吗?

  1. <code>$customSubMap = {};
  2. subscribeEvent = function ( $collection, event_name, fn ) {
  3. $collection.on( event_name, fn );
  4. if ( ! $customSubMap[ event_name ] ) {
  5. $customSubMap[ event_name ] = $collection;
  6. }
  7. else {
  8. $customSubMap[ event_name ]
  9. = $customSubMap[ event_name ].add( $collection );
  10. }
  11. };</code>

看起来第二种可读性更好一点。

其实我觉得两者本质上没区别,就像产品与分类的关系,可以说 {Product1:[Category1, Category2]}也可以说{Category1: [Product1, Product2]}

个人感觉第二

人气教程排行