2

I am using this script: https://github.com/goranefbl/jquery.tiny.modal/blob/master/jquery.tinymodal.js

in one of my functions that is fired on button press, this one:

    function fireLightbox(quarter,room_id,otherRoom) {
        $.tinyModal({
            title: "Room is free, want to book now?",
            html: '#bookRoom',
            buttons: ["Book"],
            Book: bookTheRoom(quarter) // <- the issue 
        });
    }

"Book" button that appears inside lightbox above should execute this below function, but its firing immediately when above function loads.

    function bookTheRoom(quarter) {
        console.log(quarter);
    }

I need it ofc. executed once I click on button, not once the first "fireLightbox" function is executed.

Also tried like this, it does not execute it, but also doesn't pass the variable, altho this makes sense to me that its not working

function fireLightbox(quarter,room_id,otherRoom) {
    $.tinyModal({
        title: "Room is free, want to book now?",
        html: '#bookRoom',
        buttons: ["Book"],
        Book: function(quarter) {
            console.log(quarter);
            bookTheRoom(quarter);   
        }
    });
}

Of course function works fine if I call it without () but then I don't have parameters.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Goran Jakovljevic
  • 2,714
  • 1
  • 31
  • 27

1 Answers1

5

You could return a function, then the variable you pass in will be available to the inner function through closure.

function bookTheRoom(quarter)
{
    return function()
    {
        console.log(quarter);
    }
}

EDIT - To elaborate a bit: when you call bookTheRoom(quarter), now it doesn't execute the console.log directly. Instead it returns a function that will execute console.log when called. This is a bit like your second solution above, where you associate the "Book" property with a function - the difference being that you do this through a function call, so the function that is executed on a click can access all the variables that were passed to your first function call.

My answer was intended as a "general" solution. In your particular case, since you don't seem to be changing the value of quarter, you don't even need to do this. Your second solution is good enough, just remove the quarter parameter from your function definition, and your inner function will get it from the scope of your outer function, through closure. To be clear, if quarter is not an object and you don't change quarter inside fireLightBox (or even if it is an object and you don't change it anywhere), this would also work:

function fireLightbox(quarter,room_id,otherRoom) {
    $.tinyModal({
        title: "Room is free, want to book now?",
        html: '#bookRoom',
        buttons: ["Book"],
        Book: function() {
            console.log(quarter);
        }
    });
}
Gio
  • 841
  • 1
  • 5
  • 11