Does the polymer provide a different definition of identity for data binding?

Based on “How to bind data bindings to template instances” in data binding documents to polymers, it looks like JavaScript equality is used to determine if the data is “the same” between template calls. Thus, value types have an equality value, but objects and arrays use referential equality. If I make two calls to the service, which returns an array of objects, and some of these objects have the same values ​​between calls, the template instances will be recreated, since both the array and the objects are deserialized into different instances (I checked this behavior in version 0.3.3) .

Is it possible to specify an identity function similar to how D3 uses a key function ?

+4
source share
1 answer

I don’t know if there is such a thing, but I would come up with a different solution. Let your code look something like this (pseudo code)

<ajax onResponse="{{onResponse}}" response="{{ajaxResponse}}" url="/users"></ajax>
<template repeat="{{user in ajaxResponse}}">
   <span>Hello from {{user.name}}</span>
</template>

If I understood you correctly, you said that when the request is made, the template will be re-evaluated regardless of whether there were changes in the data or not.

To fix this, we can present our data in a different way, which is evaluated not by reference, but by value.

class UserListElement extends PolymerElement {

   @observable List userIds = toObservable([]);
   Map<int, Object> users = {};

   onResponse(var response) {
      users = {};
      for(var user in response) {
        users[user.id] = user;
        if (!users.contains(user.id)) userIds.add(user.id);
      }
      var toRemove = userIds.where((user) => !_userData.containsKey(user.id));
      for(var userId in toRemove) userIds.remove(userId);
   }
}

-

<ajax onResponse="{{onResponse}}" url="/users"></ajax>
<template repeat="{{userId in users}}">
   <span>Hello from {{users[userId].name}}</span>
</template>

Like I said, not verified pseudocode. But this is the only idea I can come up with.

0
source

All Articles