Reorder the Polymer dom-repeat element following a modification in the child component's value

My Polymer dom-repeat list is working fine on the initial value sorting for the children. However, when I update a value within a child element, the sort order of the list does not reflect the changes. What is the best way to achieve this?

<body>
    <list-records></list-records>

    <dom-module id="list-records">
        <template>
            <template is="dom-repeat" 
                      items="{{records}}"
                      sort="sortByValue">
                <single-record record="{{item}}"
                               base="{{base}}">
                </single-record>
            </template>
        </template>
        <script>
            Polymer({
                is: 'list-records',
                properties: {
                    records: {
                        type: Array,
                        value: [
                            {number:1, value:4},
                            {number:2, value:2},
                            {number:3, value:3}]
                    }
                },
                sortByValue: function(a, b) {
                    if (a.value < b.value) return -1;
                    if (a.value > b.value) return 1;
                    return 0;
                }
            });
        </script>
    </dom-module>

    <dom-module id="single-record">
        <template>
            <div>
                Number: <span>{{record.number}}</span> 
                Value: <span>{{record.value}}</span>
                <button on-tap="_add">+</button>
            </div>
        </template>
        <script>
            Polymer({
                is: 'single-record',
                properties: {
                    record: Object,
                },
                _add: function() {
                    this.set('record.value', this.record.value + 1);
                }
            });
        </script>
    </dom-module>
</body>

Background: In my actual location-based application, there is a central location defined by latitude and longitude coordinates. I receive a list of keys representing locations around this center. For each key, I create a child element. These children retrieve additional information such as latitude and longitude asynchronously from a database using the provided key. By utilizing both the center's coordinates and the retrieved location info, I can calculate the distance within each child element. The desired outcome is to have the list ordered based on these calculated distances.

Answer №1

Within your single-record component, the record property is currently not set up for two-way data binding, which means any changes made to that record within the component will not be reflected back in the list-records element. To enable two-way data binding, you need to define the record property with notify:true.

properties: {
  record: {
    type: Object,
    notify: true
  }
}

For more information, check out the source: https://www.polymer-project.org/1.0/docs/devguide/properties

Answer №2

After receiving assistance from Neil, I made adjustments including adding the notify parameter and 'observe' to the template (source: How to re run dom-repeat with sort when bool property changed in Polymer element).

<template id="list"
          is="dom-repeat" 
          items="{{records}}"
          sort="sortByValue"
          observe="value">

With these changes, the code functions correctly both in the sample provided above and in the real geo-location application :)

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

Save the JSON response from JavaScript to a different file extension in a visually appealing layout

I've created a script to generate both the CSR and private key. The response displayed in the <textarea> is well-formatted with newline characters (assuming familiarity with the correct CSR/Private key format). However, I'm encountering a ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

The onChange method in React is failing to execute within the component

I am having trouble overriding the onChange method in a component. It seems like the method is not triggering on any DOM events such as onChange, onClick, or onDblClick. Below are the snippets of code where the component is rendered and the component itsel ...

Utilizing Ajax to dynamically update the content of a div element

As a newcomer to Ajax, I am trying to use xmlhttprequest to dynamically change the content of a div by fetching HTML from different URLs. However, my code doesn't seem to be working as expected. Can someone help me identify what I might be doing wrong ...

A guide on organizing dates in a datatable using the dd-MMM-yyyy hh:mm tt format

I have encountered an issue with sorting the date column in my datatable. Here is a screenshot showcasing the problem. Below is the code I am using: <table id="tbl" class="table table-small-font table-bordered table-striped"> <thead> &l ...

Node.js request.url is returning incomplete URL

I am currently testing out the code snippet provided in a beginner's book on Node.js. var http = require("http"); var url = require("url"); function onRequest(request, response) { console.log("request URL is: " + request.url); var pathName ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

Encountering the error "TypeError: Router.use() is expecting a middleware function but received undefined" when attempting to import a router from another file

Trying to configure a router for user paths and exporting it for use in index.js is causing an error. The following error message is displayed: C:\Users\yugi\OneDrive\Documents\codes\NodeJs\API_nodejs\node_modules&bs ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Implementing state management with Vue.js

After creating a login page and setting conditions to display different NAVBARs based on the user's login status, I encountered an issue where the rendering seemed to be delayed. In the login process, I utilized local storage to store a token for auth ...

Eliminate error class in jQuery Validate once validation is successful

I'm having an issue with the jQuery Validate plugin. Even after a field is successfully validated, the "error-message box" continues to be displayed. How can I remove this box? Here's my code: CSS: .register-box .field .has-error{ border ...

Customize Google Chrome to display a vibrant splash screen instead of a boring white blank page when

"I've been on the lookout for Chrome apps that can help make my screen darker or inverted to reduce eye strain. While I have found some apps that do the job, there's one thing they don't seem to be able to override - the White Blank page. W ...

Unexpected outcomes arise when parsing headers from a file-based stream

Currently, I am in the process of creating a small parser to analyze some log files using node streams (more specifically io.js). I have been referring to the documentation for unshift to extract the header. While I can successfully divide the buffer and ...

Incorporating mimes into ASP .NET MVC

Quick question: I've been trying to enable file extensions in my MVC application by editing the Web.config file, but it doesn't seem to be working. Is there anything else I need to do? <system.webServer> <staticContent> <mimeMa ...