-1

I am making some mistake on calling the function inside another function in my jQuery object. My code is something like this:

var employee = function() {
  this.init();
};

employee.prototype = {
  init: function() {
    $(document).on("click", "#addEmployee", this.addEmployee);
  },
  updateErrorMsg: function() {
    alert('Error');
  },
  addEmployee: function(e) {
    updateErrorMsg();
  }
}

I added $(document) to attach the event because the view is a partial view. I am getting the error :

Uncaught ReferenceError: updateErrorMsg is not defined

Please assist me what mistake I am doing.

Gorakh Nath
  • 9,140
  • 15
  • 46
  • 68
  • 2
    I don't see `updateModelErrorMsg` anywhere, so I guess it isn't defined .... – Bart Friederichs May 15 '18 at 07:10
  • Or use this.updateErrorMsg(); – Volkan Yılmaz May 15 '18 at 07:12
  • 2
    Voting to close as typo/non-repro/not-useful-to-others-in-future. Instead of just `updateErrorMsg`, you want `this.updateErrorMsg`. But you'll also want to read this: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback Separately: The *overwhelmingly-common* convention in JavaScript is that constructor functions like your `employee` are written with a capital first letter: `Employee`. You don't have to follow convention, but when asking for help it will make it easier for people to help you. – T.J. Crowder May 15 '18 at 07:12
  • @Satpal: `employee.updateErrorMsg` doesn't exist. It's on `employee.prototype`, not `employee`. – T.J. Crowder May 15 '18 at 07:14
  • @BartFriederichs i updated the error messag – Gorakh Nath May 15 '18 at 07:15
  • @T.J.Crowder I read the above link and tried var self=this; in costructor and tried to call like self.updateErrorMsg(),but still getting the error.If possible please post the answer for above question. – Gorakh Nath May 15 '18 at 10:03

1 Answers1

1

actually the this reference is incorrect here, you can rewrite your code like this

var employee = {
    init: function() {
        var that = this;
        $(document).on("click", "#addEmployee", that.addEmployee);
    },
    updateErrorMsg: function() {
        alert('Error');
    },
    addEmployee: function(e) {
        updateErrorMsg();
    }
}
employee.init();
Sandeep J Patel
  • 910
  • 9
  • 24