Scott Scott - 2 months ago 28
Javascript Question

Access polymer component properties from callback?

With this polymer element definition:

<script>
Polymer({
is: 'hello-world',
properties: {
dataId: {
type: String
},
value: {
type: String
}
},
ready: function() {
console.log(this.dataId);
registerCallback(this.dataId, function (data) {
var z = data.someValue;
this.value = z;
});
}
});
</script>


When it tries to set
this.value
,
this
is actually the data, not the element. I want it to set the polymer property "value" to the value of z. How can I do this?

Here is the
registerCallback()
if needed:

function registerCallback(id, callback) {
callbackMap[id] = callback;
}

Answer

There are two ways of doing it

  • As you already know this has a different meaning inside the callback so one way would be to store this(Polymer element) inside some other variable

    var self=this;
    registerCallback(function(){
       self.data = some value
    })
    
  • Second option is to bind this with your callback

    registerCallback(function(){
       this.data= some value
    }.bind(this));