Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in the last 6 months.

The issue is that on my-view2, the displayed values do not update unless the page is manually refreshed. I want the values on my-view2 to automatically update every time the page is loaded or viewed, even if it's cached.

I have provided a plnkr link showcasing my-view2 so you can better understand what I am trying to achieve.

https://plnkr.co/edit/ul4T2mduxjElCN4rUUKd?p=info

Any suggestions on how I can accomplish this?

Answer №1

To trigger an update in my-view2 when localStorage is updated, you can listen to the storage event:

<my-view-2 id="myView2"></my-view-2>
<script>
  window.onstorage = function(e) {
    if (e.key !== 'someKeyYouWant') return;
    document.getElementById('myView2').set('someProp', {
      oldValue: e.oldValue,
      newValue: e.newValue
    });
  };
</script>

For a workaround due to the storage event not being triggered on the window making the change, you can manually trigger a custom storage event like this:

saveToLs(e) {
  e.preventDefault();
  const newName = this.get('dogName');
  const ls = window.localStorage;
  const synthEvent = new StorageEvent('storage');
  const eventConfig = [
    'storage', 
    true, 
    true, 
    'myDog', 
    ls.getItem('myDog'), 
    newName
  ];

  synthEvent.initStorageEvent(...eventConfig);

  setTimeout((() => { // ensure async queue
    ls.setItem('myDog', newName);
    this.dispatchEvent(synthEvent);
  }).bind(this), 0);
}

On the receiving end, handle the storage update like this:

handleStorageUpdate(e) {
  if (e.key !== 'myDog' || e.newValue === this.get('dogName')) return; 
  this.set('dogName', e.newValue);
}

Remember to use the if statement to avoid processing duplicate updates with the same value.

Feel free to experiment with this concept using this example plunk.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for creating a table with a filter similar to the one shown in the image below

I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column format in both Business A Chaud and ...

Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div& ...

What is the process by which a JavaScript Date object is converted to a string when you log it to the

Whenever I create objects in JavaScript and output them to the console, I typically see a JavaScript object displayed. For instance: var myObj = { bla: "foo" } console.log(myObj); This code will display: { bla: "foo" } However, whe ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

Error occurred: Undefined module imported

CounterDisplay.js import React from 'react'; const CounterDisplay = <div> <h1>{this.state.counter}</h1> <button onClick={this.handleDecrement}>-</button> <button onClick={this.handleIncrement}>+ ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

What is the best way to update the context while iterating through a jQuery each loop?

I am currently working on a code snippet that preprocesses response data retrieved from an AJAX call before displaying it (note: the display part is not included in this snippet). Specifically, it updates the src attribute of the image within each li eleme ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

"The `Head.js` method called `.js()` allows for dynamic

Recently, I came across some code that was passed down to me from work, and it involves making an api call using head.js: head.js( { 'application' : 'someurl.com/foo.js' }); I'm curious if this actually registers the javascript a ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Is it possible to distinguish and identify each separate window when a user opens multiple instances of your site?

Has anyone explored the possibility of distinguishing between multiple windows a user may open on the same site? My goal is to assign the initial window the name "window1" and subsequent windows "window2" and so forth. Is there a method for achieving this ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

I am interested in extracting specific data from the JSON response

I am trying to extract the value of the message parameter under the messages array where the parameter name is equal to documentId (highlighted in bold below). However, the code I have tried so far does not achieve this as needed. dynamic obj = JsonConver ...

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

Can CSS be used for creating unique color combinations?

I am facing a challenge where I have two div elements with different transparent, colored backgrounds that overlap each other. My goal is to find a way to customize the color in the area where these elements overlap. For instance, if I blend red and blue ...

Script on Tampermonkey executed prior to page loading

I am facing a challenge with hiding a specific section from an HTML page: <h1 data-ng-show="!menuPinned &amp;&amp; !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX&nbsp;</span><span style="font-weight: bold;"& ...

Unable to retrieve scripts upon returning to the main page of a Jquery website

Starting fresh with this post, I'm feeling incredibly frustrated and close to giving up on JQM completely. This shouldn't be so difficult. Here's my website structure: OUI/ index.php js/ pages/ images/ On the index.php page at http://loca ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...