Search code examples
javascriptdata-bindingpolymerweb-componentpolymer-1.0

How to expose local variables with Polymer 1.0 dom-bind


I've created a polymer element that needs a canvas 2d context as attribute to work, and I'm trying to get it from a sibling canvas tag.

I've seen https://www.polymer-project.org/1.0/docs/devguide/templates.html, but it doesn't answer my issue.

Here is what I have done for now:

<body>
<template id="app" is="dom-bind">
    <my-element id="renderer" context="{{ context }}"></my-element>
    <canvas id="rendering-canvas"></canvas>
</template>
<script>
    (function (document) {
        'use strict';
        var app = document.querySelector('#app');

        app.addEventListener('template-bound', function () {
            console.log('Our app is ready to rock!');
        });

        window.addEventListener('WebComponentsReady', function () {
            document.querySelector('body').removeAttribute('unresolved');

            var renderer = document.querySelector('my-element[id=renderer]'),
                canvas = document.querySelector('canvas[id=rendering-canvas]');

            app.context = canvas.getContext('2d');
        });
    })(document);
</script>
</body>

Edit: MyElement

Polymer({
        is : 'my-element',
        properties: {
            type: {
                type: String,
                value: 'Text'
            },
            context: {
                type: CanvasRenderingContext2D
            }
        }
    });

My main issue is how to to something like context="canvas.getContext('2d')" ? Right now the my-element's context property is not set.


Solution

  • <my-element id="renderer"></my-element>
    <canvas id="rendering-canvas"></canvas>
    
    <script>
        (function (document) {
            'use strict';
    
            window.addEventListener('WebComponentsReady', function () {
                document.querySelector('body').removeAttribute('unresolved');
    
                var renderer = document.getElementById('renderer'),
                    canvas = document.getElementById('rendering-canvas');
    
                renderer.context = canvas.getContext('2d');
            });
        })(document);
    </script>