如何访问与在Polymer中可见的相同“事件”中的模板内容

时间:2015-05-08 09:32:30

标签: templates polymer

让我试着找出我的问题

<polymer-element name="my-element">
    <template>
        <template if="{{show}}">
            <my-other-element id="elementWithUnexposedInternals"></my-other-element>
        </template>
    </template>
    <script>
        Polymer({
            show: false,
            showChanged: function{
                this.$.elementWithUnexposedInternals.someProperty = true;
            }
        });
    </script>
</polymer-element>

似乎my-other-element在这个。$ line中是不可访问的,因为模板还没有呈现它。

如何解决这个“订单”问题?

干杯

2 个答案:

答案 0 :(得分:0)

您可以在'domReady'事件监听器中为'show'设置值。

答案 1 :(得分:0)

实际上,你有两个问题。一个是元素尚未渲染,另一个是元素将永远不会添加到this.$,而<polymer-element name="my-element"> <template> <div id="container> <template if="{{show}}"> <my-other-element id="elementWithUnexposedInternals"></my-other-element> </template> </div> ... var el = this.$.container.querySelector('#elementWithUnexposedInternals'); 仅填充元素&#39; s < em>静态内容:

https://www.polymer-project.org/0.5/docs/polymer/polymer.html#automatic-node-finding

您可以通过添加静态容器并使用querySelector来解决第二个问题:

async

至于时间安排。在Polymer 0.5中,数据绑定更新使用微任务计时(在当前事件处理程序之后,在处理下一个事件之前)。正如您所看到的那样,在数据绑定模板标记其内容之前,将调用已更改的处理程序。

您应该可以通过延迟使用 showChanged: function(){ this.async(function() { var myEl = this.$.container.querySelector("#elementWithUnexposedInternals"); myEl.someProp = true; }); }, 访问元素来解决此问题。结合这两个修复,你得到:

setTimeout(function, 0);

async也可能有用 - 您需要做的就是在事件循环中延迟一个循环。但this在Polymer中更为惯用(另外,它调用绑定到自定义元素实例的 public function show($id) { $product= Product::findOrFail($id); return View('product.show')->with('product',$product); } 的回调,这很方便)。

这里的工作示例:http://jsbin.com/gicado/1/edit?html,output