jQuery Once

by Kyle Mitofsky

HTML

<div>
    <input value='Hey There!' />
    <input value='Tab or Click!' />
</div><br/>

<div>
    Changed: <span id="changedPlaceholder"></span> 
</div>
<div>
    On: <span id="onPlaceholder"></span> 
</div>
<div>
    One: <span id="onePlaceholder"></span> 
</div>
<div>
    Once: <span id="oncePlaceholder"></span> 
</div>
<div>
    Only: <span id="onlyPlaceholder"></span> 
</div>



















<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;    
            background:lightgray;width:100%;'>
    About this SO Question: <a href='http://stackoverflow.com/q/24589084/1366033'>jQuery's One - Fire once with multiple event types</a><br/>         
<div>

JavaScript

$.fn.once = function (events, callback) {
    //The handler is executed at most once per element for all event types.
    return this.each(function () {
        $(this).on(events, myCallback);
        function myCallback(e) {
            $(this).off(events, myCallback);
            callback.call(this, e);
        }
    });
};

$.fn.only = function (events, callback) {
    //The handler is executed at most once for all elements for all event types.
    var $this = $(this).on(events, myCallback);
    function myCallback(e) {
        $this.off(events, myCallback);
        callback.call(this, e);
    }
    return this
};


$('input').once('mouseup keyup', function(e){ 
    console.log(e.type);
    console.log(this);
});





var changed = false;
var on = one = once = only = 0


$(":input").on('change',function() {
    changed = true;
    on += 1;
    setChangedText();
});

$(":input").one('change',function() {
    changed = true;
    one += 1;
    setChangedText();
});

$(":input").once('change',function() {
    changed = true;
    once += 1;
    setChangedText();
});

$(":input").only('change',function() {
    changed = true;
    only += 1;
    setChangedText();
});



setChangedText();
function setChangedText() {
    $("#changedPlaceholder").text(changed);    
    $("#onPlaceholder").text(on); 
    $("#onePlaceholder").text(one); 
    $("#oncePlaceholder").text(once); 
    $("#onlyPlaceholder").text(only); 
}



// event logger
$("input").on("mousedown mouseup keydown keyup", 
              function(e) {
     console.log(e.type + ' logged');
});