TypeError: "this..." is not a function

SoftTimur picture SoftTimur · Jul 7, 2017 · Viewed 15.1k times · Source

I define hostService as follows. The senario is I call first hostService.addListener() in the controller, then the controller may emit a message by $rootSceop.$emit, hostService is supposed to handle it.

app.service('hostService', ['$rootScope', function ($rootScope) {    
    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            this.button()
        })
    }

However, the problem is the above code raises an error:

TypeError: this.button is not a function

Does anyone know how to fix it?

Answer

Damián Rafael Lattenero picture Damián Rafael Lattenero · Jul 7, 2017

I solve this creating a self variable with this object, then you can call it from diferent scope:

app.service('hostService', ['$rootScope', function ($rootScope) {    

    var self = this

    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            self.button()
        })
    }