Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does knockoutJS support protected observable array?

Tags:

knockout.js

What is the best way to handle an observable array which can be committed/thrown away in KnockoutJS?

I've achieved this before with the ProtectedObservable idea but this was on a single record of data, not on an array.

Just wondered how to best go forward. My project requires a dialog of all email address contacts and a list of those selected. As they are added from a list on the left, they are removed and get added to a list on the right.

When the 'ok' button is pressed, they are added into the To: field but when 'cancel' is pressed the lists are restored to their previous state (which could already have been populated before).

like image 631
jaffa Avatar asked Jun 07 '11 09:06

jaffa


1 Answers

How about something like this: http://jsfiddle.net/rniemeyer/PAzVk/

This uses an observableArray that supports "snapShots". You can save a copy of the underlying array and restore it whenever you need to.

ko.snapShotObservableArray = function(initialData) {
    var _snapShot = initialData;
    var result = ko.observableArray(initialData || []);

    result.takeSnapShot = function() {
        _snapShot = this().slice();  //take a copy of the underlying array
    };

    result.restoreSnapShot = function() {
       this(_snapShot.slice());   
    }

    return result;
}

In the sample, you would use this on you array of available users, array of selected users, and array of users on the "To" line. Then, the cancel button restore each array back to the point that you took the last snapshot.

like image 173
RP Niemeyer Avatar answered Oct 30 '22 03:10

RP Niemeyer