How to tell when Polymer is done with all the data-binding?

Sachin Hosmani

Let's say I have a Polymer element x-foo which uses templates for data-binding.

<template>
  <!--shadow DOM-->
  <template repeat='{{item in items}}'>
    <div class='content'>{{item}}</div>
  </template>
</template>

items is a property of x-foo which decides what is present in the view.

Now, on the fly in one of the methods of x-foo I do:

this.items = getNewItemList();

and then try to access shadow DOM content,

this.shadowRoot.querySelectorAll('.content') // was supposed to return 5 elements

I find that Polymer still hasn't iterated through the template loop and generated my shadow DOM content. Is there a way to know when it has finished it?

Scott Miles

By design, Polymer waits until your JavaScript has finished processing before it does expensive things like messing with DOM. That way you can do several operations at once and not worry about thrashing DOM and slowing down your application.

The short answer to your question is to do something like this:

this.items = getNewItemList();
this.async(
  // `async` lets the main loop resume and perform tasks, like DOM updates,
  // then it calls your callback 
  function() {
    this.contents = this.shadowRoot.querySelectorAll('.content'); 
  }
);

A better answer is to avoid needing to query for the elements. Instead, let the elements communicate with the container via events or even using the 'item' objects (the data model). If you can drive your UI from your data-model, and not the reverse, you will have a better time.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related