Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset jQuery one() so that it will fire again

Tags:

jquery

I'm using the jQuery one() method on an event handler to fire once then de-register itself. Something like:

$(".main").one('mousedown', '.resizeBar', function (e) { /* my code */ });

Then some ajax (actually, a .net postback) resets most of the page (without reloading) and I want to set up the event handler again. Is there a way to either re-set the one() event handler to be active again? Manually re-triggering it this way doesn't work, obviously:

$(".main .resizeBar").trigger("mousedown");
like image 703
brentonstrine Avatar asked Aug 03 '12 17:08

brentonstrine


2 Answers

just wrap that code in a function

function mainMouseDownOne() {
    $(".main").one('mousedown', '.resizeBar', function (e) { /* my code */ });
}

$(document).ready(function(){
    mainMouseDownOne();

    .ajax({
        ...
        success: function() {
            ...
            mainMouseDownOne();
        }
    })
});
like image 158
hackattack Avatar answered Oct 19 '22 07:10

hackattack


I would recommend wrapping the one() method bind inside a function call, then you can call the function (to bind the initial event handlers) on page load, and again on success of the Ajax call.

var bindEvents = function(){
  $(".main").one('mousedown', '.resizeBar', function (e) { /* my code */ });
};

$(function(){ bindEvents(); }); // call the one() method on page load.

$.post(pageURL, function(data){
  bindEvents(); // As an example, after some sort of Ajax or post-reset event.
});
like image 21
Joe Johnson Avatar answered Oct 19 '22 06:10

Joe Johnson