Add DjlJson element

Still rudimentary, liable to change

* Add supporting example.json
* Include some basic examples in example.html
This commit is contained in:
Dylan Lom 2021-05-27 01:17:05 +10:00
parent fe3d7465ae
commit a02cc85b7f
3 changed files with 57 additions and 1 deletions

41
DjlJson.js Normal file
View File

@ -0,0 +1,41 @@
/**
* Retrieve content from remote JSON source
* Displays textContent while loading, then replaces with JSON response
* @property {string} src - URI to remote JSON
* @property {string} prop - Property of JSON to display
* @property {string} placeholder - Interim content to display while retrieving and reading JSON
*/
// TODO: Add callback prop
// TODO: Add attributeChangedCallback and re-fetch
// TODO: Allow accessing local objects
class DjlJson extends HTMLElement {
src; // string
prop; // string
placeholder; // string
constructor() {
super();
this.src = this.getAttribute('src')
this.prop = this.getAttribute('prop').split('.')
this.placeholder = this.textContent
fetch(this.src)
.then(resp => {
if (!resp.ok)
throw new Error(`Unabled to retrieve resouce ${this.src} (${resp.statusText})`)
return resp.json()
})
.then(json => this.getProp(json, this.prop))
.then(prop => this.textContent = prop)
.catch(err => { console.error(err); this.textContent = err })
}
getProp(obj, prop) {
if (!prop.length) return obj
return this.getProp(obj[prop[0]], prop.slice(1))
}
}
customElements.define('djl-json', DjlJson)

View File

@ -5,8 +5,9 @@
<title>Web Components Example.</title>
<!-- TODO: Use your own style sheet? -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/yegor256/tacit@gh-pages/tacit-css-1.5.1.min.css"/>
<script defer src="DjlScript.js"></script>
<script defer src="DjlJson.js"></script>
<script defer src="DjlLipsum.js"></script>
<script defer src="DjlScript.js"></script>
</head>
<body>
@ -35,5 +36,12 @@
<p><djl-script>['This','is','a','djl-script','element', '(click', 'on', 'me', 'to', 'edit).'].join(' ');</djl-script></p>
<p><djl-script>`Happy ${['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'][new Date().getDay()]}day`</djl-script></p>
</article>
<article id="djl-json">
<p>My name in example.json is: <djl-json src="example.json" prop="about.name">loading...</djl-json></p>
<p>My pets are called: <djl-json src="example.json" prop="about.pets">loading...</djl-json></p>
</article>
</article>
</body>
</html>

7
example.json Normal file
View File

@ -0,0 +1,7 @@
{
"about": {
"name": "Dylan Lom",
"dob": "2020-10-09T00:00:00+1000",
"pets": [ "Banjo", "Big Bird" ]
}
}