devpunks / snuggsi

snuggsi ツ - Easy Custom Elements in ~1kB
https://snuggsi.com
MIT License
395 stars 17 forks source link

Update Documentation for `context`, `initialize`, `onconnect`, & `onidle` #188

Closed snuggs closed 4 years ago

snuggs commented 5 years ago

@0xhjohnson has bought to our attention the need for documentation of intermediate API features. We actually have documentation @ http://snuggsi.herokuapp.com/#lifecycle However a little vague to access as domain name is not pointed to heroku instance. Also as @brandondees the "Site is janky" and perhaps need to start thinking of documentation outside of Github.

AN async/await example (like below) could be some nice eye candy as well. Best part of the snuggsi element is it's just a class which in itself is syntactic sugar for a bunch of methods. Therefore technically every member method of a snuggsi element can be async/await. SUPER HANDY when needing to say fetch data from an API in initialize or onconnect. Don't forget about those async button actions that are usually a pain in the butt.

Dependencies

References

Example

Refactor

<hello-world>Coin of the day: {coin}</hello-world>

<script src=//unpkg.com/snuggsi></script>
<script src=https://unpkg.com/axios/dist/axios.min.js></script>
<script>
// Element Definition -----------------------------

Element `hello-world`

// Class Description ------------------------------

(class extends HTMLElement {

  initialize ()  // context
    { this.context.coin = 'Bit'  }

  onidle (e)
    { console.log ('Happens after each render') }

  async onconnect (e) {  // event handler for when custom element is connected to DOM

    // Just like jQuery...or any other DOM event handler for that matter
    // One side effect is this prevents rendering which occurs after ALL event handlers.
    e.preventDefault () // or return false

    let // Deconstructing Assignment
        // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
      { response : { data : { chartName : coin } } }
        = await axios.get ('//api.coindesk.com/v1/bpi/currentprice.json')

    this.context.coin = coin
    console.log (this.context.coin)
  }

  get coin () // element properties are bound to tokens. * NOT CONTEXT*
    { return this.context.coin }
})
</script>