How to create a custom Web Component, simply

It had been a long time I wanted to try HTML5 WebComponents and this week I finally had the time.

So I'll explain how to create your own custom webcomponent. However you need to know that there are still problems to be settled on the implementation of all HTML5 APIs necessary in order to create a reusable component (e.g. HTML Imports).

I create a simple application using Brick from Mozilla, LESS, Coffeescript (with the Cake compiler) and play with all that stuff into the nice Brackets Editor. The application here just displays a deck with 4 cards and a widget that shows a text and updates its content when clicking on it.

Summary:

  • Brick integration
  • CSS integration
  • Coffeescript/Javascript integration

First things first, we start with the html markup.

You'll see in the listing that I used the x-deck, x-card widgets from the Mozilla Brick library and I create a you-brick component with a template.

  <x-deck selected-index="0" id="deck_1" loop>
    <x-card>
      <p>Card 1 : Hello world! We're testing WebComponents !</p>
    </x-card>
    <x-card>Card 2</x-card>
    <x-card>Card 3</x-card>
    <x-card>Card 4</x-card>
  </x-deck>

  <your-brick>My brick with default content.</your-brick>

  <template id="test-template">

    <!-- CSS RULES HERE -->
    <style>
      div{
        padding: 2em;
        background: #D9F9D9;
        font-size: 2em;
        height: 20%;
      }
    </style>
    <!-- HTML CONTENT -->
    <div data-content>Template content.</div>

  </template>

Then this is the Coffeescript:

document.addEventListener "DOMComponentsLoaded", () ->

  $("x-deck").click () ->
  @.nextCard()

  xtag.register("your-brick",
  extends: "div"
  lifecycle:
    created: () ->
      @count = 0
      $(@).html($("#test-template").html())
      console.log "loaded"
  events:
    click: (e) ->
      @count++
      console.log "click"
      template = $("#test-template").html()
      @.innerHTML = template
      $(@).find("[data-content]").text("You've just clicked "+@count+" time(s) on your new custom WebComponent")
  )

You can find more details about the Web Component lifecycle at http://www.x-tags.org/docs.

Don't hesitate to contact me at contact[at]christianbarras[dot]com, I can send you all sources under a zip file.