【问题标题】:Instantiating Web Components from JS从 JS 实例化 Web 组件
【发布时间】:2014-03-06 00:01:21
【问题描述】:

我正在尝试直接从 Javascript 实例化 Web 组件,但系统找不到公共构造函数。我将举一个简单的例子来展示上下文和结果:

HTML 模板:

<polymer-element name="wc-foo" constructor="Foo" noscript>
    <template>
       Hello World!
    </template>  
</polymer-element>

HTML 索引:

<html>
<head>
    <script src="general/scripts/polymer/polymer.min.js"></script>
    <link rel="import" href="...">
</head>

<body>  
</body>

<script>
    console.log (window); // (1)
    console.log (window.Foo); // (2)
    var foo = new Foo (); // (3)
</script>

</html>

控制台结果:

(1) 我检查了窗口对象,它包含构造函数 Foo: function (){return f(a)} (2) 我不知道但 window.Foo 返回 undefined 是什么 (3) ...因此,new Foo() 失败:Uncaught ReferenceError: Foo is not defined

有人可以帮助我了解问题是什么? 谢谢。

【问题讨论】:

    标签: javascript polymer web-component


    【解决方案1】:

    您需要等待 polymer-ready 事件触发以确保 Polymer 已完成设置:

    document.addEventListener('polymer-ready', function() {
      console.log (window.Foo); // (2)
      var foo = new Foo (); // (3)
      console.log(foo)
    });
    

    演示:http://jsbin.com/dabaloso/1/edit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-30
      • 2019-01-07
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多