xrforge/manyfold/usr/src/app/public/view/element/janus-script-fetch.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

room.registerElement("fetch",{
interval: 0,
to: "",
url: "",
selector: "",
append: false,
prefix: "",
loader: "loading..",
createChildren: function(){
let el = this.children[0]
if( !this.to ) return console.warn("<fetch> has no 'to' attr")
if( !this.children.length ) return console.warn("<fetch> needs one child element")
if( !el[this.to] ) el[this.to] = this.loader
if( this.append ) this.prefix = el[ this.to ]
this.fetch()
if( this.interval ) setInterval( () => this.fetch, this.interval * 1000 )
},
fetch: function(){
const finalUrl = `${elation.engine.assets.corsproxy||''}${this.url}`
fetch( finalUrl )
.then( (res) => res.text() )
.then( (text) => {
this.text = text
this.updateChild()
})
},
updateChild: function(){
let el = this.children[0]
let result = this.text
if( this.selector ){
let div = document.createElement("div")
div.innerHTML = this.text
let partial = div.querySelector(this.selector)
if( partial ){ result = partial.outerHTML
}else result = "oops..remote content<br>not available"
}
el[ this.to ] = this.append ? this.prefix + result : result
}
})