Attach a jquery event after object is created

249 views Asked by At

I am using the bPopup jquery library.. the syntax to add to the onclose event is pretty straightforward:

$('element_to_pop_up').bPopup({
     onOpen: function() { alert('onOpen fired'); }, 
     onClose: function() { alert('onClose fired'); }
})

What I want to do is add something to the onClose event after the object is created.. is it possible?

4

There are 4 answers

2
Vigneswaran Marimuthu On BEST ANSWER

You can access the bPopup object which will be present inside the data of the element.

$('element_to_pop_up').bPopup({
    onOpen: function() { alert('onOpen fired'); }, 
    onClose: function() { alert('onClose fired'); }
});

$('element_to_pop_up').data('bPopup');

NOTE: There is no guarantee that the created object will be always present in element's data. But this is widely used approach. It is better to rely on the callback provided.

0
Tom K On

In general you can do this by creating a function that you fiddle with later:

var myOnClose = function() { alert('onClosed fired'); }
function doOnClose() { myOnClose(); }

$('element_to_pop_up').bPopup({
    onOpen: function() { alert('onOpen fired'); }, 
    onClose: doOnClose
})

// later...
myOnClose = function() { console.log("Doing something different!"); }
0
ch271828n On
var realOnclose = f1;
function myOnClose(){realOnclose();}
 $('element_to_pop_up').bPopup({ 
    onOpen: function() { alert('onOpen fired'); },
    onClose: myOnClose
})

function f1() { alert('onClose fired'); } 
function f2() { alert('hey I am another function'); } 

//when you want to change the action when onclose...
realOnclose = f2;
0
John S On

If you want to add to, rather than replace, the code you originally supply to the onClose option, you could trigger a custom event:

$('element_to_pop_up').bPopup({
    onClose: function() {
        // Do the original stuff here.
        this.trigger('popup:close');
    }
});

Then, at any time later, you can register a handler for the custom event:

$('element_to_pop_up').on('popup:close', function() {
    // Do the additional stuff here.
});

Note: Looking at the code for the bPopup library, it looks like the context for the onClose function is the original jQuery object, but if it isn't, replace with: $('element_to_pop_up').trigger('popup:close');.