Property change not reflecting in UI when its set

2019-07-03 06:33发布

问题:

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

回答1:

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');



回答2:

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) {


回答3:

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