0

I have object with data array and mark_read method, which sends PUT request to my Rails app. It looks like this in data option is not the object instance, how can I fix it?

Notifications.prototype = {
  constructor: Notifications,
  ...
  mark_read: function() {
    $.ajax({
      method: "PUT",
      url: '/notifications/mark_read',
      data: this.data.slice(0,5)
    });
  }
  ...
}
Nonemoticoner
  • 650
  • 5
  • 14
Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62

2 Answers2

0

You should store "this" in a closure before trying to access it from inside of $.ajax function.

It should be something like this

Notifications.prototype = {
  constructor: Notifications,
  ...
  mark_read: function() {
      var me = this;
      $.ajax({
          method: "PUT",
          url: '/notifications/mark_read',
          data: me.data.slice(0,5)
      });
  }
  ...
}
Evgeny Sorokin
  • 630
  • 3
  • 12
0

The scope for this is the mark_read function, so the context for this is whatever Notification object mark_read() is called upon.

szym
  • 5,606
  • 28
  • 34