【问题标题】:Inject html in polymer including data binding在聚合物中注入 html,包括数据绑定
【发布时间】:2017-02-14 22:43:15
【问题描述】:

我有一个带有数据绑定的受信任 html 文件,我想将它包含到 Web 组件中。我尝试了多种方法来包含该 html 文件,但数据绑定不起作用。我知道聚合物不会标记 html,因为它会成为来自不受信任来源的 XSS 攻击的漏洞,但我有一个受信任的来源。

我已经知道12 并尝试了juicy-html、iron-ajaxinner-h-t-m-l 以及injectBoundHTML 函数。

除了自己绑定所有东西,还有别的办法吗?

我要包含的文件包含输入字段,它是一个预定义的表单。

【问题讨论】:

    标签: javascript html data-binding polymer inject


    【解决方案1】:

    您可以通过手动创建<template> 并设置其内容来使用Templatizer。重要的部分是你不能只设置innerHTML

    Polymer({
      is: 'my-elem',
      behaviors: [ Polymer.Templatizer ],
      ready: function() {
    
        var template = document.createElement('template'); 
        
        // you must prepare the template content first (with bindings)
        var templateContent = document.createElement('div');
        templateContent.innerHTML = 'First: <span style="color: red">[[person.first]]</span> <br> Last: <span style="color: green">[[person.last]]</span>';
        
        // and cannot simply set template's innerHTML
        template.content.appendChild(templateContent);
        
        // this will process your bindings
        this.templatize(template);        
        var person = {
          first: 'Tomasz',
          last: 'Pluskiewicz'
        };
        var itemNode = this.stamp({ person: person });
        
        Polymer.dom(this.root).appendChild(itemNode.root);
      }
    });
    <!DOCTYPE html>
    <html>
    
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.19/webcomponents.min.js"></script>
        <link rel="import" href="https://raw.githubusercontent.com/Polymer/polymer/master/polymer.html" />
      </head>
    
      <body>
        <my-elem>
        </my-elem>
           
        <dom-module id="my-elem">
          <template>
          </template>  
        </dom-module>
      </body>
    
    </html>

    【讨论】:

    • 我试过你的 sn-p 并且它有效。模板内的数据绑定正在工作。是否可以标记复杂的对象?也没有与外部元素的数据绑定。冲压只在一个方向。 var itemNode = this.stamp({ i: this.data });数据={名称=“亚历克斯”}
    • 是的,您可以绑定任何对象(请参阅更新)。两种方式绑定是可能的,但很棘手。看到这个垃圾箱:jsbin.com/kipato/edit?html,js,output
    • 感谢您提供的示例。数据绑定现在可以工作了:) 你知道如何传递事件吗?这些字段是触发事件,但外部上下文看不到它们。
    • 我发现了问题。当我创建它时,该元素会在就绪状态下触发一个事件。我将其更改为附加,现在它工作正常:) 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多