domReady vs ready - Migrating to Polymer 1.0

坚强是说给别人听的谎言 提交于 2019-12-11 02:43:25

问题


In Polymer0.5, I had the following code:

Template:

<div class="scroll">
    <div class="content">
        <content></content>
    </div>
</div>

Script:

domReady: function() {
    var width = $(this.shadowRoot).find('.content')[0].scrollWidth;
}

This code worked, and I received a non-zero value for the width.


Now I am trying to migrate to Polymer1.0, I added an ID to the div:

<div class="scroll">
    <div id="content" class="content">
        <content></content>
    </div>
</div>

And the script is now:

ready: function() {
    var width = this.$.content.scrollWidth;
}

However, this width is 0.


Is there a difference between the old domReady function, and the new ready function? I have also tried using the attached function but it did not work either.

When I try to access the width later on (triggered by a button press), then I get the non-zero value I am looking for.


The element is used like this:

<my-scrollbar>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam purus leo, sagittis lobortis velit vel, viverra vulputate purus. Proin lacinia magna eu erat iaculis, eget mollis lectus mattis. 
</my-scrollbar>

So that inner text is what determines the dimensions of the element.


回答1:


It turns out that my original code was working in Safari, but not in Chrome.

With Zikes suggestion, I added in some async, and now it works in both browsers.

Final answer:

attached: function() {
    this.async(function(){
        var width = this.$.content.scrollWidth;
    },1)
}



回答2:


An alternative is to "flush" the DOM before working with it. In this case, the code would be:

attached: function() {
  var width;
  Polymer.dom.flush();
  width = this.$.content.scrollWidth;
},

Since this is synchronous, declarative, and doesn't involve closures, it could be easier to work with.

More information: https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#dom-api



来源:https://stackoverflow.com/questions/30607541/domready-vs-ready-migrating-to-polymer-1-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!