Friday, 30 September 2016

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




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



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()
})
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...