Search code examples
javascripttelevisionwebosenyo

WebOS 3.0 Access to UI from function


I cannot access to enyo Ui component from function:onComplete in WebOS 3.0.

buttonTapped: function(inSender, inEvent) {
    console.log("Button is clicked");
    this.$.txt.setContent(inSender.name + " tapped."); // This worked
    var request = webOS.service.request("luna://com.webos.service.tv.systemproperty", {
        method: "getSystemInfo",
        parameters: {"keys": ["modelName", "firmwareVersion", "UHD", "sdkVersion"]},
        onComplete: function (inResponse) {
            var isSucceeded = inResponse.returnValue;
            if (isSucceeded){
               console.log("Result: " + JSON.stringify(inResponse));
               $.txt.setContent("Result: "+JSON.stringify(inResponse)); // This is not worked
            }
        }
    });
...

Console output

Button clicked
Result{"modelName":"WEBOS1","firmwareVersion":"03.00.00","UHD":"false","sdkVersion":"03.00.00","returnValue":true} 
Uncaught TypeError: Cannot read property 'txt' of undefined 

I not found any documentation about this.


Solution

  • The reason for the error is that your callback function is not executing in the context of your component. this is not your component (not to mention you're missing the keyword this in front of $.txt...).

    What you need to do is bind the context of the callback function or use it to create a closure over a variable that contains a reference to this.

    This is a such a common occurrence that Enyo provides a utility method for this: this.bindSafely.

    Try the following:

    onComplete: this.bindSafely(function (inResponse) {
        var isSucceeded = inResponse.returnValue;
        if (isSucceeded){
            console.log("Result: " + JSON.stringify(inResponse));
            this.$.txt.setContent("Result: "+JSON.stringify(inResponse));
        }
    })
    

    See: http://enyojs.com/docs/latest/#/kind/enyo/CoreObject/Object:bindSafely