wormhit
wormhit

Reputation: 3827

Polymer non blocking asynchronous function that is linked to template

I have template

<core-list data="{{ list }}" height="80">
    <template>
        <app-list-item transaction="{{ transaction }}"></app-list-item>
    </template>
</core-list>

and js part that sets this.list data

# Polymer("app-list", {

ready: function() {
    this.list = null;
},
activeChanged: function(oldValue, isActive) {
    if (isActive == "1") {
        this.initialize();
    }
},
initialize: function() {
    var response = this.fetchListData();
    this.list = response.data;
}

I can trigger initialize() when template element is activated using attributeChangedCallback() (by click of the button)

I'm getting this.list data from external API using XMLHttpRequest() and this request takes time.

So when I'm pushing the button to activate my element application freezes for view seconds.

Is there a way to create some kind of callback method that will populate this.list only as soon as API data arrives? Until then this.list should stay as null.

Upvotes: 0

Views: 505

Answers (1)

ebidel
ebidel

Reputation: 24109

A good way to do this is with <core-ajax>:

<core-ajax auto url="http://www.google.com/calendar/feeds/[email protected]/public/full?alt=json" handleAs="json" response="{{list}}"></core-ajax>
<core-list data="{{ list.feed.entry }}" height="80">
  <template>
    <div>{{title.$t}}</div>
  </template>
</core-list>

Demo: http://jsbin.com/nasibiqe/1/edit

The auto attribute tells core-ajax to make its request as soon as the element is ready. Then, we data bind core-list's data attribute to the ajax's response attribute. This only populates the list when data is available. If you instead want to make the XHR request when a button is pressed, remove the auto attr:

<core-ajax id="ajax" url="..." handleAs="json" response="{{list}}"></core-ajax>
<button on-click="{{go}}">Go</button>

go: function() {
  this.$.ajax.go();
}

Demo: http://jsbin.com/giwujija/1/edit

Upvotes: 4

Related Questions