Search code examples
javascriptdojo

function() is not a function in dojo


I am getting this error when calling a function in dojo:

TypeError: this.loadNameAndDescpFromLookup is not a function

But I dont know why ?: here is my code

readBarcodeFromMobile: function(){
        stompClient.subscribe('/topic/messages', function(event) {
            registry.byId('PId').set("value", event.body);
            this.loadNameAndDescpFromLookup(event.body); // the error is here
        });
    });
}            

loadNameAndDescpFromLookup: function(barcode){ }

Any ideas?


Solution

  • Like the others pointed out, the problem is that this doesn't refer to the object you want to use inside of the function.

    The solution would be to store the this context in the variable and refer to it later.

    For example

    readBarcodeFromMobile: function(){
    const self = this; // save the `this` context in a variable
    this.socket = SockJS('/controller/Barcode');
    this.sockets.push(this.socket);
    stompClient = Stomp.over(this.socket);
    stompClient.connect({}, function(frame) {
        stompClient.subscribe('/topic/messages', function(event) {
          if(registry.byId('productBarcodeId') != undefined){
            registry.byId('productBarcodeId').set("value", event.body);
            self.loadNameAndDescpFromLookup(event.body); // use the stored context
          }
        });
     });
    } 
    loadNameAndDescpFromLookup: function(barcode){ }