te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Vanilla Web Component custom event attributes and properties - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vanilla Web Component custom event attributes and properties - Stack Overflow

programmeradmin3浏览0评论

Using Web Components without any framework, what is the proper way to implement a custom event? For example, say I have a custom element x-pop-out that has a custom event of pop I would want all of the following to work:

<x-pop-out onpop="someGlobal.doSomething()"/>

var el = document.getElementsByTagName('x-pop-out')[0];
el.onpop = ()=> someGlobal.doSomething();
//or
el.addEventListener('pop', ()=> someGlobal.doSomething());

The last one I get how to do, but do I need to custom implement the attribute and a getter / setter for each? Also, is eval() the appropriate way to execute the string from the attribute?

Using Web Components without any framework, what is the proper way to implement a custom event? For example, say I have a custom element x-pop-out that has a custom event of pop I would want all of the following to work:

<x-pop-out onpop="someGlobal.doSomething()"/>

var el = document.getElementsByTagName('x-pop-out')[0];
el.onpop = ()=> someGlobal.doSomething();
//or
el.addEventListener('pop', ()=> someGlobal.doSomething());

The last one I get how to do, but do I need to custom implement the attribute and a getter / setter for each? Also, is eval() the appropriate way to execute the string from the attribute?

Share Improve this question edited Feb 20, 2017 at 9:47 Supersharp 31.2k11 gold badges101 silver badges147 bronze badges asked Feb 18, 2017 at 22:44 hapticdatahapticdata 1,6711 gold badge13 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

The event listener solution (the third one) is the easiest because you don't have to define anything special to catch the event.

The event handler solutions need to make an eval() (first one, from attribute) or to call the fonction explicitely (second one).

If you can't use eval you can instead parse the attribute string.

customElements.define( 'x-pop-out', class extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<button id="Btn">pop</button>`

        this.querySelector( 'button' ).onclick = () => {
            this.dispatchEvent( new CustomEvent( 'pop' ) )
            if ( this.onpop )
                this.onpop()
            else
                eval( this.getAttribute( 'onpop' ) )
        }            
    }
} )

XPO.addEventListener( 'pop', () => console.info( 'pop' ) )
<x-pop-out id=XPO onpop="console.log( 'onpop attribute' )"></x-pop-out>
<hr>
<button onclick="XPO.onpop = () => console.log( 'onpop override' )">redefine onpop</button>

Based on SuperSharp answer. His suggestion would only work for console logs and not actually the events. The solution I used was to override dispatchEvent and made it to also create custom HTML event attributes.

Following the standard of using 'on' + event.type. We mask the attribute in a new function using with and check if the attribute is a function and pass in the event if required.

dispatchEvent(event) {
  super.dispatchEvent(event);
  const eventFire = this['on' + event.type];
  if ( eventFire ) {
    eventFire(event);
  } else {
  const func = new Function('e',
    'with(document) {'
       + 'with(this) {'
         + 'let attr = ' + this.getAttribute('on' + event.type) +';'
         + 'if(typeof attr === \'function\') { attr(e)};
       + }'
     + '}'
   );
   func.call(this, event);
   } 
}

Example:

class UserCard extends HTMLElement {

  constructor() {
    // If you define a constructor, always call super() first as it is required by the CE spec.

    super(); //

  }


  dispatchEvent(event) {
    super.dispatchEvent(event);

    const eventFire = this['on' + event.type];
    if (eventFire) {
      eventFire(event);
    } else {
      const func = new Function('e',

        'with(document) {' +
        'with(this) {' +
        'let attr = ' + this.getAttribute('on' + event.type) + ';' +
        'if(typeof attr === \'function\') { attr(e)};' +
        '}' +
        '}');
      func.call(this, event);
    }

  }

  connectedCallback() {
    this.innerHTML = `<label>User Name</label> <input type="text" id="userName"/>
   <label>Password</label> <input type="password" id="passWord"/>
    <span id="login">login</span>`;
    this.test = this.querySelector("#login");
    this.test.addEventListener("click", (event) => {
      this.dispatchEvent(
        new CustomEvent('pop', {
          detail: {
            username: 'hardcodeduser',
            password: 'hardcodedpass'
          }
        })
      );
    })


  }

}

customElements.define('user-card', UserCard);

function onPop2(event) {
  debugger;
  console.log('from function');
}
<user-card id="XPO" onpop="onPop2"></user-card>
<hr>
<user-card id="XPO" onpop="console.log('direct Console')"></user-card>

发布评论

评论列表(0)

  1. 暂无评论