Search code examples
jquerythisjquery-blockui

Using "this" inside of jQuery functions


I have created a CalendarViewerPortlet custom object JS object. In this object, I am storing things like the portlet's id and its context path. The object also has many custom methods, some to get/set the member variables and some to do specific things.

When I try to reference a function of the object using "this." inside of a jQuery function, it blows up. I get that the term "this" in that context is probably referring to something else, but I am not sure how to get around the problem and have it reference the object, as I want it to.

Here is the offending code:

jQuery.ajax({
  url: jQuery(formSel).attr("action"), 
  type: "POST", 
  data: jQuery(formSel).serialize(), 
  beforeSend: function(xhr) {
  jQuery(msgSel).hide();
  jQuery(msgSel).html("");
  jQuery(tableSel).hide();
  jQuery(pagerSel).hide();
  jQuery(cpSelector).block({
  message: "<img src='"+this.getContextPath()+"/images/icon_loading.gif' align='absmiddle' alt='Loading...' /> Fetching events..."
  });
},

NOTE the "this.getContextPath()". That is where the code is failing. I am trying to reference the getContextPath() function of my custom object. How can I do that?


Solution

  • The problem is the code this.getContextPath() is executed later in an anonymous function passed as on option to ajax() function. So the 'this'(your custom JS object) you want will not be available at the point of the execution of the method. You can store it in a variable and let the function 'closure' the reference. The following should work:

    var calendarViewer = this;
    
    jQuery.ajax({
      url: jQuery(formSel).attr("action"), 
      type: "POST", 
      data: jQuery(formSel).serialize(), 
      beforeSend: function(xhr) {
      jQuery(msgSel).hide();
      jQuery(msgSel).html("");
      jQuery(tableSel).hide();
      jQuery(pagerSel).hide();
      jQuery(cpSelector).block({
      message: "<img src='"+calendarViewer.getContextPath()+"/images/icon_loading.gif' align='absmiddle' alt='Loading...' /> Fetching events..."
      });
    },