首页 > 试题广场 >

标题:钩子函数 题目描述:请实现一个钩子函数,钩子函数可以理

[问答题]
标题:钩子函数
题目描述:请实现一个钩子函数,钩子函数可以理解为事件被动地被监听着,一旦满足条件就执行,可以执行多次(被监听到多次)
class Emitter{
    constructor(ele){
        this.ele=ele
    }
    on(event,func){
        this.ele.addEventListener(event,func)
    }
    off(event,func){
        this.ele.removeEventListener(event,func)
    }
}
var ele=document.getElementsByClassName('one')[0]
var one=new Emitter(ele)
function my(){
    console.log("123")
}
one.on('click',my);
// one.off('click',my);  // 清除事件
发表于 2020-04-16 15:59:22 回复(1)
import React, {component} from 'react'

export default class Listener extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            count:1
        }
    }
    componentDidMount() {
        window.addEventListener('click',this.handle)
    }
    
    componentWillUpdate() {
        window.removeEventListener('click', this.handle)
    }
    
    handle = () => {
        if(this.state.count >1) {
            this.setState({
                count: count+1
            })
        }
    }
    
    render() {
        return (
            <div>
             <button onClick={this.handle}>submit</button>
            </div>
        )
    }
} 

发表于 2020-01-07 16:09:31 回复(0)
class EventEmitter {
  constructor() {
    this._observerList = []
  }
  
  subscribe(observerFunc) {
    if (!observerFunc instanceof Function) throw new Error('param must be a function')
    return this._observerList.push(observerFunc) 
  } // end subscribe
  
  notify() {
    this._observerList.forEach(func => func())
  } // end notify
} // end EventEmitter

const _eventEmitterInstance = new EventEmitter()

_eventEmitterInstance.subscribe(()=>console.log('one'))

_eventEmitterInstance.subscribe(()=>console.log('two'))

_eventEmitterInstance.subscribe(()=>console.log('three'))

_eventEmitterInstance.notify()

发表于 2019-12-08 06:53:17 回复(1)