[英]Polymer error “A type with that name is already registered” using Polymer.Base.importHref
[英]Dynamically Load HTML page using Polymer importHref
我正在編寫一個使用Polymer 1.0的輔助函數importHref()
加載html文件的簡單元素。 頁面加載完畢,但不是[html渲染[object HTMLDocument]
頁面,而是[object HTMLDocument]
。
當我記錄成功的回調時,導入的頁面將包裝在#document
對象中(不確定此處的術語)。 但是,信息就在控制台中。
因此,我的問題是:如何將html呈現到頁面?
元件:
<dom-module id="content-loader">
<template>
<span>{{fileContent}}</span>
</template>
<script>
Polymer({
is: "content-loader",
properties: {
filePath: {
type: String
}
},
ready: function() {
this.loadFile();
},
loadFile: function() {
var baseUrl;
if (!window.location.origin)
{
baseUrl = window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
else
{
baseUrl = window.location.origin;
}
//import html document and assign to fileContent
if(this.filePath)
{
this.importHref(baseUrl + this.filePath, function(file){
this.fileContent = file.target.import;
console.log(this.fileContent); //logs fine
},
function(error){
console.log(error);
});
}
}
});
</script>
正在使用:
<content-loader file-path="/app/general/contact.html"></content-loader>
<span>{{fileContent}}</span>
會將fileContent
呈現為字符串,這就是為什么您看到[object HTMLDocument]
(這是在document
Object上調用toString()
時得到的)的原因。
通常,Polymer不允許您綁定到HTML或節點內容,因為這存在安全風險。
您擁有的fileContent
是一個document
,這意味着它是DOM節點的集合。 您使用該文檔的方式取決於您加載的內容。 呈現節點的一種方法是將fileContent.body
附加到本地DOM上,如下所示:
Polymer.dom(this.root).appendChild(this.fileContent.body);
這是一個更完整的示例( http://jsbin.com/rafaso/edit?html,output ):
<content-loader file-path="polymer/bower.json"></content-loader>
<dom-module id="content-loader">
<template>
<pre id="content"></pre>
</template>
<script>
Polymer({
is: "content-loader",
properties: {
filePath: {
type: String,
observer: 'loadFile'
}
},
loadFile: function(path) {
if (this.filePath) {
console.log(this.filePath);
var link = this.importHref(this.filePath,
function() {
Polymer.dom(this.$.content).appendChild(link.import.body);
},
function(){
console.log("error");
}
);
}
}
});
</script>
</dom-module>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.