0

this is inside my view model.

self.Notifications = ko.observableArray(); // loaded by ajax

self.MarkAsFlagged = function(item) { //updates the item in Notifications
        console.log('MarkAsFlagged');
        var index = self.Notifications.indexOf(item);
        console.log(index);

        var flagStatus = item.Flagged; // current flagstatus
        item.Flagged = !flagStatus; // set true if false and viceversa

        flagStatus = !flagStatus;// set true if false and viceversa
        self.Notifications.replace(self.Notifications()[index], item);
}

this is my html

<ul data-bind="foreach: Notifications "  >
 <li>
   <span data-bind="text: Name" style="font-weight: bold;"></span>       
   <div style="float: right; width:15px;">
       <input type="image" id="" data-bind="click:function(){$parent.MarkAsFlagged($data)},css: {flagged: Flagged==true, unFlagged: Flagged==false }" style='float:right;padding-right:3px;' />
   </div>
 </li>
</ul>

when i click the MarkedAsFlagged and replace the item on self.Notifications() the ui is not changing.

the ui only responses when i remove any item from the array. please help here.

1 Answer 1

1

Item props in Notifications array is not observable. So, when you change it in MarkAsFlagged, ui is not updated. You should create own model for item with observable props:

function ItemModel(data) {
    var self = this;
    self.Name = ko.observable(data.Name);
    self.Flagged = ko.observable(data.Flagged);
}

function ViewModel() {
    var self = this;
    self.Notifications = ko.observableArray();

    self.loadNotifications = function() {
       // loading data...

       var itemModels = _.map(data, function (item) {
           return new ItemModel(item);
       }); 
       ko.utils.arrayPushAll(self.Notifications(), itemModels);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

it says "_" is not defined. i am using knockout 2.1 . is there anything missing?
thanks i used $.map and it is working. thanks very much
can u edit your answer, your self.loadNotifications() at last line must be a typo?
yep, it's a bug, i've changed to self.Notifications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.