1

I have 3 functions on an object prototype:

Job.prototype.postData = function(url) {
  this.getFormData();
  var formdata = new FormData();
  formdata.append("position", this.position);
  formdata.append("team", this.team);
  formdata.append("details", this.details);
  $.post(url, formdata, function(response) {
    alert(response.message);
    window.location.href = '/';
  });
};

Job.prototype.createNew = function() {
  var newUrl = API_URL + "/add_listing";
  this.postData(newUrl)
};

Job.prototype.update = function() {
  var updateUrl = API_URL + "/edit_listing" + "?id=" + this.id;
  this.postData(updateUrl)
};

I'm attaching the last two as event handling callbacks:

$('#list-button').on('click',job.createNew);
$('#list-button').on('click',job.update);

Both of those give a TypeError:

oop.js:38 Uncaught TypeError: this.postData is not a function

Rick
  • 3,308
  • 9
  • 20
  • 33
ayushgp
  • 4,045
  • 3
  • 29
  • 67

1 Answers1

1

The problem is simply that the this context gets lost the way you're binding the event handler.

Either explicitly bind the context, or call the function in a way that preserves the context:

$('#list-button').on('click', function () { job.createNew(); });
$('#list-button').on('click', job.createNew.bind(job));

See How does the "this" keyword work?.

Community
  • 1
  • 1
deceze
  • 471,072
  • 76
  • 664
  • 811