0

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

Tricky
  • 400
  • 7
  • 16
  • I've posted my current solution, however if you know of a better one please post it and i will accept if valid – Tricky Oct 05 '16 at 12:14
  • 1
    This isn't a jquery-ui specific issue. More solutions in http://stackoverflow.com/questions/3630054/how-do-i-pass-the-this-context-to-a-function – blgt Oct 05 '16 at 13:12

1 Answers1

0

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

Tricky
  • 400
  • 7
  • 16