0

I like to keep my code as DRY as possible and would like to know if the following is possible. I'll need to reuse the code below many times with the only difference being what I do in the following function.

.on("click", "a", function(e) {})

I could just duplicate the addToBooking function, give it a different name, make the slight change in the click handler but that feels wasteful and repetitive.

Can I perhaps pass a code block to the addToBooking function? Or maybe there's another cool, efficient way I'm not aware of.

The full code block

var addToBooking = function(that, event) {
  var left, top;

  event.stopPropagation(); 

  //Turn off all calendar tracking
  $(".track").off(); 

  //Get proper sticky positioning (Checks to make sure it wont display off screen)
  left = getPosition(".add_to_booking", "left");
  top = getPosition(".add_to_booking", "top");

  //Position sticky, display and listen for click event to see what to do next
  $(".add_to_booking").css({top: top, left: left})
                      .fadeIn('fast')
                      .on("click", function(e) { e.stopPropagation(); })
                      .on("click", "a", function(e) {
                        if($(this).text() === "YES") {
                          //Close dialog
                          closeTT();

                          //Open new add to booking box
                          addBooking(that, event);

                        } else {
                          closeTT();
                        }
                      });
}

1 Answer 1

2

Pass in the function and assign it

var addToBooking = function(that, event, custFnc) {
    ...
    ...
    .on("click", "a", custFnc );
}

Fiddle

To pass parameters, you need to use call()

jQuery( function(){

    function hey(evt, test){ 
        var text = jQuery(this).text();
        alert(text + ":" + test);
    }


    function addClick( custFnc ){ 
        var test=99;
        jQuery("#foo").on("click", 
            function(e){ 
                custFnc.call(this, e,test); 
            } 
        );
    }

    addClick(hey);
});

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

In your example, how would I pass variable from that function? See here, it doesn't work but you get the idea: jsfiddle.net/SqZm4/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.