Use a global variable in Polymer dom-if

157 views Asked by At

I am creating a custom module for Polymer. I need to create a global variable that can be accessed when defining a template. Something like:

<template is="dom-if" if="[[_check(myGlobalVar.foo)]]">

The global variable should also be directly accessible from inside the module (see _anotherFunction) . The JS file looks like:

Polymer({
    is: 'my-module',

    _check(f) {
        return f == 'foobar'
    },

    _anotherFunction() {
        console.log(myGlobalVar)
    }
})

In addition, myGlobalVar should be accessible from other modules in other files. What's the best way to create it?

2

There are 2 answers

0
Vin On

You can achieve that in two ways.

  1. Have a component that can hold all the global variables and gives the same instance of its data where ever it is used. You can find the better explanation using link along with working sample

  2. If you have lot of data that needs to be accessible globally then the best option would be using store with polymer-redux.

0
Rickard Elimää On

There is a specific Polymer element for this.

iron-meta is a generic element you can use for sharing information across the DOM tree.

https://www.webcomponents.org/element/@polymer/iron-meta

The element fires value-changed if a value has been changed, so you probably need to set up values for it.


We don't use it in our company however, but just storing the value in memory, and then send an event whenever we set the value. Also adding a listener for every element that needs to listen to updates.