使用原生JS做一个jQuery的one方法

jQuery的 one 方法很好用,在给函数绑定事件的时候,可以在事件触发一次的时候,就取消掉事件绑定,这样有两个好处,一是有的需求是 只希望完成事件被触发第一次时产生效果,二是事件监听是浪费资源的,这样可以只在需要的时候监听

代码如下:

function once(dom, type, callback) {  
    var handle = function() {  
        callback() 
        dom.removeEventListener(type, handle)
    }  
    dom.addEventListener(type, handle)  
}  

亲测有效


写到原型链上

Element.prototype.once = function(type, callback) {  
    var handle = function() {  
        callback()  
        this.removeEventListener(type, handle)
    }  
    this.addEventListener(type, handle)  
} 

使用示例如下

oDiv.once('click', function(){
  ... // 代码
})

意外发现这个里面的 this 默认是window,和原生的(函数内部的this是触发事件的元素)不一样

现更正代码如下

Element.prototype.once = function(type, callback) {  
    var handle = function() {  
        callback = callback.call(this)
        this.removeEventListener(type, handle)
    }
    this.addEventListener(type, handle)
} 

你可能感兴趣的:(使用原生JS做一个jQuery的one方法)