Search code examples
javascriptpolymer

Passing Current Polymer Object (this) into a Callback Function


What's the best way to pass the current object to a callback function?

I have been using something like:

var that = this;

For example:

<link rel="import" href="/bower_components/polymer/polymer.html">
<polymer-element name="stackx-example">
    <template>
        <div id="container">{{innards}}</div>
    </template>
    <script>
        Polymer('stackx-example', {
            ready: function() {
                var jax = new XMLHttpRequest();
                jax.open('GET', '/jaxson/testing/', true);
                jax.send();
                var that = this;
                jax.onreadystatechange = function(){
                if (jax.readyState == 4 && jax.status == 200) {
                    that.innards = jax.responseText;
                }
            }
            },
            innards: '..missing'
        });
    </script>
</polymer-element>

Solution

  • You can make use of Function.prototype.bind() to set the this value within the callback to the same this value used outside the callback:

    jax.onreadystatechange = function() {
      if (jax.readyState == 4 && jax.status == 200) {
        this.innards = jax.responseText;
      }
    }.bind(this);
    

    As a bit of a tangent, this is a great opportunity to use <core-ajax> instead of a plain XMLHttpRequest. It will lead to more idiomatic Polymer code:

    <polymer-element name="stackx-example">
      <template>
          <div id="container">{{innards}}</div>
    
          <core-ajax auto
                     url="/jaxson/testing/"
                     handleAs="text"
                     response="{{innards}}">
          </core-ajax>
      </template>
    
      <script>
          Polymer({
            innards: '..missing'
          });
      </script>
    </polymer-element>