Skip to content

<:Window> component #371

@Rich-Harris

Description

@Rich-Harris

I often find myself doing this sort of thing:

<div><!-- stuff --></div>

<script>
  export default {
    data () {
      return {
        width: window.innerWidth,
        height: window.innerHeight
      };
    },

    oncreate () {
      const onresize = () => this.resize();
      window.addEventListener( 'resize', onresize, false );
  
      this.on( 'teardown', () => {
        window.removeEventListener( 'resize', onresize, false );
      });
    },

    methods: {
      resize () {
        this.set({
          width: window.innerWidth,
          height: window.innerHeight
        });
      }
    }
  };
</script>

Lots of boilerplate, and it's easy to forget to remove the event listener when the component is destroyed.

Occurs to me we could have a special <:Window/> component (using the convention started with <:Self/>), that behaved thusly:

<:Window on:resize='resize()'/>
<div><!-- stuff --></div>

<script>
  export default {
    data () {
      return {
        width: window.innerWidth,
        height: window.innerHeight
      };
    },

    methods: {
      resize () {
        this.set({
          width: window.innerWidth,
          height: window.innerHeight
        });
      }
    }
  };
</script>

Or even this...

<:Window on:resize='set({ width: this.innerWidth, height: this.innerHeight })'/>
<div><!-- stuff --></div>

<script>
  export default {
    data () {
      return {
        width: window.innerWidth,
        height: window.innerHeight
      };
    }
  };
</script>

Or even this:

<:Window bind:innerWidth='width' bind:innerHeight='height'/>
<div><!-- stuff --></div>

Lots of other events that would be useful — on:offline, on:hashchange and so on. A lot of them could have their own bindings: bind:hash, bind:online, bind:scrollTop (in fact that one could apply to regular elements, not just window) and so on.

Similarly:

<:Document on:fullscreen='set({ isFullscreen: this.fullscreen })'/>

<!-- or... -->
<:Document bind:fullscreen='isFullscreen'/>

The glorious thing about being fully compiled is we can kind of go nuts with this stuff without anyone needing to install extra components or ship code they don't need. The only cost we need to worry about is documentation and maintenance cost.

Interested to hear what people think of these ideas.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions