jquery-uijquery-ui-widget-factory

Scoping issue with jQuery UI Widget Factory


I have a scoping problem that i cannot find a solution for in Google here is a simplified version of my code

jQuery.widget( "myNamespace.myPlugin", {

  options: {},

  _create: function() {
    $main = this.element;
  },
  
  _init: function() {
    $main.text('ajax running');
    $.ajax({url:'some/url/path'})
    .done(function(data) {
      this._callback(data);
    });
  },
  
  _callback: function() {
    
    $main.text('ajax complete');
  }

});

$('.widget_element').myPlugin();
<html>
  <head>
    <script
			  src="https://code.jquery.com/jquery-2.2.4.min.js"
			  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
			  crossorigin="anonymous"></script>
    <script
			  src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
			  integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
			  crossorigin="anonymous"></script>
		
  </head>
  <div class="widget_element"></div>
</html>

The error i am getting is:

TypeError: this._callback is not a function

Is there a better way of performing this task in within the widget environment?

Thanks


Solution

  • As with most problems, a solution only rears its head AFTER you post a question on SO

    Aparently self = this is perfectly valid

    jQuery.widget( "myNamespace.myPlugin", {
    
      options: {},
    
      _create: function() {
        self = this;
        $main = this.element;
      },
      
      _init: function() {
        $main.text('ajax running');
        $.ajax({url:'some/url/path'})
        .done(function(data) {
          self._callback(data);
        });
      },
      
      _callback: function() {
        
        $main.text('ajax complete');
      }
    
    });

    I hope this helps someone in the future