Targeting events outside of templates/components

by rich_harris

HTML

<main></main>

<script id='template' type='text/ractive'>
    <p id="component" on-click='clickedInside'>Click Me
        <br/>
        <br/>
        <span>Target: {{target}} template/component</span>
    </p>
</script>

CSS

body, html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    font: bold 20px/1 'Helvetica Neue', arial, sans-serif;
    background-color: #eee;
    overflow: hidden;
}
#component {
    position: relative;
    margin: 25px 0 0 25px;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    background-color: goldenrod;
    color: white;
    cursor: pointer;
}
#component span {
    position: absolute;
    left: 0;
    bottom: 20px;
    width: 200px;
    text-align: center;
    font-size: 12px;
    line-height: 1;
    text-transform: uppercase;
    color: black;
}

JavaScript

var ractive = new Ractive({
    el: 'main',
    template: '#template',
    data: {
        target: 'no click yet on'
    }
});

ractive.on( 'clickedInside', function ( event ) {
    event.original.stopPropagation(); // stop the window getting the event
    this.set( 'target', 'clicked inside' );
});

window.addEventListener( 'click', function ( event ) {
    ractive.set( 'target', 'clicked outside' );
});