Search code examples
arraysuser-interfaceobservablenativescriptjavascript-objects

NativeScript updating UI on ObservableArray change


I have NativeScript vanillaJS app with list of items (as array) and "like" button on the side to update data in the array which should reflect to UI but it does not. When ever I call function sendFeedback() it should change data in the array what should reflect as a change in the UI but that's not the case.

Here is my object with Observable array:

let viewModel = observableModule.fromObject({      
    myData: new ObservableArray.ObservableArray([])
});  

myData receives data with content:

     [{
        "id": "43", 
        "itemStatus": "negative"
      }, {
        "id": "44", 
        "itemStatus": "negative"
     }]

My View is:

<ListView items="{{ myData }}">
    <Label class="{{ 'list-item ' + (itemStatus === 'positive' ? ' fas': ' fal') }}" tap="sendFeedback" idArtikla="{{ id }}" stanjeFav="{{ itemStatus }}" text="Send feedback" height="40"/>   
</ListView>

Here is my Module function:

function sendFeedback(args){
    const status        = args.object; 
    const itemStatus     = status.itemStatus; 
    if(stanjeFav === "negative"){ 
        viewModel.myData[0].itemStatus = "positive";
        // some other code here  
    } else {  
        viewModel.myData[0].itemStatus = "negative";
        // some other code here
    }   
}

exports.sendFeedback = sendFeedback;

I have list with 50+ items and on the item tap I want to switch the class. Can someone help me with pointing me in the correct direction please. I have more complex code behind but this is just enough to give you idea.

Thanks!


Solution

  • ObservableArray is only responsible for monitoring changes like on Array (like adding new item, removing existing one).

    It doesn't detect changes on attributes within a item, you will have to refresh the list or use Observables inside ObservableArray.

    new observableArrayModule.ObservableArray([
      observableModule.fromObject({ name: "Hello", tapped: false }),
      observableModule.fromObject({ name: "World", tapped: false })
    ])
    

    Playground Sample