سؤال

I call a function to open a dialog box when the user clicks on a "customize" link. The function has a callback when the user clicks "save" button. This callback returns an obj. My issue is when you click "customize" 1 time, you get returned the obj once, 2 times, returns twice, 3 returns 3... on and on.

I what is the callback to return only once after each time user clicks "customize".

$(document).ready(function(){

    $('#customize_link').click(function(){
        var child_id = $(this).attr('child-id') * 1,
        this_box = boxJson[child_id]['boxList'][0];

        customize_box(this_box, function(obj){
            boxJson[child_id]['boxList'][0] = obj;
            box_dialog.dialog('close');
       });
    });
}); // end of doc.ready

function customize_box(obj, callback){

    // bunch of code modifying obj...

    $('#save_box_button').click(function(){
        if(typeof callback == "function"){
            return callback(obj);
        }
    });
}

The vars (child_id, this_box) get instantiated only once for each click, but the customize_box has the obj returned the count(clicks) 2, 3, 4, n... as many times box_customize_link is clicked.

How can I get the obj back only once for each box_customize_link click?

هل كانت مفيدة؟

المحلول

the click handler on $('#save_box_button') gets attached every time you call customize_box which is every time $('#customize_link') is clicked.

instead of $('#save_box_button').click(function(){ you should use

$('#save_box_button').one("click", function() { ...

that way, the click handler only gets attached once.

A second option would be to remove the possibly present click handler before you reattach it:

$('#save_box_button').off("click.savehandler").on("click.savehandler", function() { ...

notice the domain "savehandler". it prevents other click events from being detached by the off-method which i think is a good practice using this method.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top