Computed Binding Not Detecting Change in Iron List - polymer

Polymer 1, I have in iron-list:
<iron-list
id="ironList"
scroll-target="[[ironListScrollTarget]]"
items="[[itemCollectionCopy]]">
...
<div class="text center-justified info-icon">
<iron-icon
hidden="[[!_isDirtyData(item.*, itemCollectionCopy)]]"
role="img"
aria-label="Check-out information has been modified"
title="Check-out information has been modified"
icon="icons:info-outline"></iron-icon>
<iron-icon
hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]"
role="img"
class="pristine-data"
aria-label="Check-out information has been modified"
title="Check-out information has been modified"
icon="icons:info-outline"></iron-icon>
</div>
_isDirtyData: function(item) {
console.log(item);
return item.base.preferences;
},
setCustomPreference: function(e) {
const id = e.detail.data.clientId;
const preferences = e.detail.data.preferences;
const foo = this.itemCollectionCopy.map((item) => {
if (item.client_id === Number(id)) {
item.preferences = preferences;
}
return item;
});
this.itemCollectionCopy = [];
this.itemCollectionCopy = [...foo];
},
When adding a preferences object to item.preferences, I could not get the computed binding hidden="[[_isDirtyData(item.*)]]" to detect a change. Instead, I had to add the whole array itemCollectionCopy in hidden="[[_isDirtyData(item.*, itemCollectionCopy)]]" which seems excessive.
Why wouldn't the computed binding detect a change with just hidden="[[_isDirtyData(item.*)]]"?

The way polymer is observing changes in property is not perfect, and they added some array mutations methods to change array and notify templates of this changes.
You can use them if they work for your particular case.
https://polymer-library.polymer-project.org/1.0/docs/devguide/model-data#work-with-arrays
Sometime you want to perform operation in a JS way, or just there is no array mutation method adapted for your case.
There is a notifyPath method which can help also.
this.notifyPath('myarray.*');
for example will trigger all corresponding observers.

Related

Data Bindings across template tags

I'm wondering, is there a possibility to have databindings "out of" a template? Say I have a <template/>-Tag somewhere which I put into the slot of a different component - that component stamps it to its context. Then I want to bind data from the root element to the <template/>-Tag. Also, event bindings (on-x-changed) don't work, because you can't assign a function which is defined in the hosting component. Any ideas?
Example:
... host
{{boundData}}
<binding-component>
<template>
{{boundData}}
</template>
</binding-component>
I don't see changes when I observe boundData in the hosting component. Is there a way to get around this? Or is firing a custom event my only chance?
If you are looking for binding a property outside of polymer something like from index.html you may bind value with element. an example ; index.html
<dom-bind>
<template>
<binding-component bound-data="{{boundData}}"></binding-component>
</template>
</dom-bind>
<script>
// set a value a string, Number or Object etc.
// Optionally wrap this code into a listener ie;
// window.addEventListener('load', e=> { ...below code ... })
var boundData= document.querySelector('dom-bind');
boundData = {} //
</script>
Now in your binding-component element has a property as boundData
hope its helps or provide more code to understand better.
I've made it work the way dom-if does it, too. Like in dom-if (reference), I'm creating a Templatize-instance which then uses forwardHostProp to handle the "inside"-properties
this.__ctor = Templatize.templatize(template, this, {
mutableData: true,
forwardHostProp(prop, value) {
// handling item updates, item being the only property
// from within the binding component
// everything else is automatically bound by templatize
this.set(prop, value);
this.update(this.item);
},
});
this.__instance = new this.__ctor();
this.root.appendChild(this.__instance.root);
This all happens in connectedCallback.
Because the Templatize-instance is passed this, it's bound to the current context as well.
Good luck!

Stamping Template Async? Race condition issue

Polymer 1.7
Is stamping a template a async operation? It's not I/O so I don't know why it would be. However, there is a race condition here where this.$$('#uploadedImage1') is undefined. It works if I use <div hidden="[[foo]]"> instead of template is="dom-if", so this is how I know it is a race condition.
<template is="dom-if" if="[[uploadedImage1]]">
<div id="uploadedImage1" class="row-image horizontal layout">
</div>
</template>
...
ready: function(e) {
function readURL(e) {
var el = e.target.id
var uploadedID = e.target.dataset.uploaded;
var file = Polymer.dom(e).localTarget.files[0];
var reader = new FileReader();
reader.onloadend = ()=> {
this[uploadedID] = true;
//RACE CONDITION HERE
this.$$('#uploadedImage1').style.backgroundImage = `url(${reader.result})`;
}
reader.readAsDataURL(file);
}
this.$['images-container'].addEventListener('change', readURL.bind(this), false)
}
Short answer: yes, template stamping is async. Here, you could use an attribute binding to style to apply the background image directly, so you don't need to manipulate the stamped DOM.
If you really need to get at the stamped DOM, you can either a) wait for a dom-change event, or b) force a synchronous render by calling render. (The latter is usually an anti-pattern--you don't want to force something to happen synchronously if you don't have to.)
https://www.polymer-project.org/1.0/docs/devguide/templates#synchronous-renders
https://www.polymer-project.org/1.0/docs/devguide/templates#dom-change
Note the docs as written may imply that only dom-repeat is rendered async, but render and dom-change are available on both elements.
Hope that helps.

Property change not reflecting in UI when its set from dom-repeat's function - Polymer

I have array of objects and a property, my dom-repeat structure is like as below
<template is="dom-repeat" items="{{arrayOfObj}}"> //first dom repeat
<span>[[myProperty]]<span> //here also its not updating
<template is="dom-if" if="[[_checkSomeCondition()]]"> //calling method from dom-if
<span>[[myProperty]]<span> //here its not getting updated value
</template>
</template>
I have a property
properties:{
myProperty:{
type:Boolean
}
}
my function is called each time when dom-repeat iterates
_checkSomeCondition:function() { //I'll check and set property
if(some condition){
this.myProperty = true;
return true;
}
else{
this.myProperty = false;
return true;
}
console.log(this.myProperty); //I'll get the updated value on console
}
but its not changing in screen!! It will display whatever data it set first time inside _checkSomeCondition !! but in console its updating
For testing I inserted a button and after all dom-repeat rendered on tapping that button I called some function ,there when I changed value it get reflected everywhere
this.myProperty = true;
but why its not working when value is changed inside a function which is called by dom-repeat?? I tried all 3 ways of updating a object
Plunker:https://plnkr.co/edit/iAStve97dTTD9cv6iygX?p=preview
Setting a variable via this.myValue = 'somevalue'; won't update binding.
Its best to set variables via this.set('variablename', 'variablevalue');
You could also, after setting a property via this.variablename = 'variablevalue'; this.notifyPath('variablename');
Try
<template is="dom-if" if="[[_checkSomeCondition(myProperty)]]"> //calling method from dom-if
<span>[[myProperty]]<span> //here its not getting updated value
</template>
And then
_checkSomeCondition: function(property) {
I have modified your code like below. Im not sure if it helps for your senario. Please have a look may help to bring up ideas
<template is="dom-repeat" items="{{sensor.Sensor.Contaminants}}" index-as="index">
<span>{{myProperty}}<span> //here also its not updating
<div>{{_checkSomeCondition(index)}}<div> //here its not getting updated value
</template>
And your _checkSomeCondition method will be:
_checkSomeCondition: function() { //I'll check and set property
console.log(index);
if(<your condition>){
this.myProperty = 'true';
} else{
this.myProperty = 'false';
}
// Return whatever you want to show in UI
return this.myProperty;
console.log(this.myProperty); //I'll get the updated value on console
},
and your myProperty should notify the changes. So the property should have notify: true.
With this code i could see the changes in the UI as expected. Let me know if it helps

Polymer - Updating Element

I'm learning Polymer. One item that is challenging me is updating the item of an array. I wish there was a CDN for Polymer so I could put together a fiddle. For now though, I have an element defined like this:
my-element.html
<dom-module id="my-element">
<button on-click="onLoadData">Load Data</button>
<button on-click="onTest1Click">Test 1</button>
<button on-click="onTest2Click">Test 2</button>
<template is="dom-repeat" items="[[ data ]]" as="element">
<div><span>[[ element.id ]]</span> - <span>[[ element.status ]]</span></div>
<template is="dom-repeat" items="[[ element.children ]]" as="child">
<div> <span>[[ child.id ]]</span> - <span>[[ child.status ]]</span></div>
</template>
</template>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
data: {
type: Array,
value: function() {
return [];
}
}
},
onLoadData: function() {
// Generate some dummy data for the sake of illustration.
for (var i=1; i<=3; i++) {
var element = {
id: i,
state: 'Initialized',
description: ''
};
element.children = [];
for (var j=1; j<=5; j++) {
var child = {
id: i + '-' + j,
state: 'Initialized',
description: ''
}
element.children.push(child);
}
data.push(element);
}
},
// Setting an individual property value works
onTest1Click: function() {
this.set('data.0.children.0.state', 'data set');
},
// Setting an entire object value does NOT work.
onTest2Click: function() {
var c = this.data[0].children[0];
c.state = 'data set';
this.set('data.0.children.0', c);
}
});
</script>
</dom-module>
For some reason, if I update the property value of an array element (as shown in onTest1Click), the UI is updated properly. However, if I update an entire element (as shown in onTest2Click), the UI does NOT get updated. In my real problem, I'm updating multiple properties on an element. For that reason, I'm trying to update an array element and not just a property. Am I doing something wrong or misunderstanding something? Or, am I going to have to update each property value individually?
If you want to mutate an array, rather than just an object in an array (such as swapping out an entire element in an array), there are array mutation methods similar to this.set.
For example, this.splice('data.0.children', 0, 1, c) will remove the current item at the 0 index of the child array and replace it with a new one, which is what it appears you're trying to do. There's also this.shift, this.unshift, this.push and this.pop. These are all similar to their Array prototype counterparts.
One thing to note is that in your example, you're also not actually swapping out the entire object. When you grab the element from the array, mutate a field, and try and replace it with itself, you're not actually replacing it, so that doesn't actually trigger an update. And since the mutation of the field was done outside of Polymer's notification system, that also doesn't trigger an update. If you replace the item with an actual different object, it will work using splice.
https://jsbin.com/rapomiyaga/1/edit?html,output (This is a modified snapshot of Günter Zöchbauer's jsbin)
If you're not making a copy of the object/a completely new object, you'll want to update each field individually through this.set.
Yes, you are going to need to update each property value individually. When you call set, Polymer will go to the given path and check if the value has changed. If the value is an object it will compare the references (and not the subproperties). Since the object reference has not changed, it will not update the UI.

repeat over list of object declaratively

I have yet another question:
Why is that if I repeat over a list of objects from a template the element in the template cannot see the object when used declaratively?
artists = [ {name: 'whatever',..},...];
Example:
<template repeat="{{a in artists}}">
<artist-record model="{{a}}"></artist-record>
</template>
If I do the same imperatively it works
Example
artists.forEach(function(a) {
var node = document.createElement('artist-record');
node.model = a;
this.$.container.appendChild(node);
}, this);
Is there a way to do this declaratively?
This works for me: http://jsbin.com/zemawugu/1/edit
Check that your array assignment is to this.artists and not artists. The binding system needs that array to be on the element prototype for the template to see it.