javascriptfunctionthisdom-eventscolorbox

Some problems with Javascript functions and this argument


I am using colorbox to my popups and...

This works fine.

$(".show_popup").colorbox({inline:true, width:"800px", onOpen: function() {
   type = $(this).attr('type);
   ....
}

But I want use my inner function many times so I want make it a module function.

});

(function ($,a) {
 var p = {
   showPopup: function (popup_type) { 
    ...
   },

   bindEvents: function () {
       $(".show_popup").colorbox({inline:true, width:"800px", onOpen: p.showPopup($(this).attr('type')) }); 
   }
...
}
a.Popups = p;
})(jQuery);

But this don't work - it is problem with $(this) - and function execute only once after page loading.

(function ($,a) {
  var p = {
   showPopup: function (popup_type) { 
    ...
   },

   bindEvents: function () {
       $(".show_popup").colorbox({inline:true, width:"800px", onOpen: p.showPopup }); 
   }
...
}
a.Popups = p;

})(jQuery);

And this don't work of course too, but execute many times. So can you help me know what is matter?


Solution

  • The problem with onOpen: p.showPopup($(this).attr('type)) is that it will run the p.showPopup-function at the moment that you bind it to onOpen. What you want is that it runs at the moment the onOpen-event is triggered. Use

    onOpen: function() { p.showPopup($(this).attr('type')); }
    

    instead

    (edit) assuming that p.showPopup is defined, I can't see it in your code.