Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Updating or inserting an item in an observable array #41

Closed
luv2code opened this Issue · 7 comments

2 participants

@luv2code

this situation is that objects are pumped from a service one at a time and stored in an array. Also, updates to those objects are received one at a time. When there is a key defined for the mappedObservableArray, it would be nice if fromJS inserted or updated based on key match.

for instance:

   var vm =ko.mapping.fromJS( [ ko.mapping.formJS({name:'matt', age:20}) ], {
        key:function(data) {
            return ko.utils.unwrapObservable(data.name);
        }
    });

    ko.mapping.fromJS(ko.mapping.fromJS({ name: 'jim', age: 23 }), vm); //should insdert jim into the array

    ko.mapping.fromJS(ko.mapping.fromJS({ name: 'matt', age: 23 }), vm); //should change matt's age to 23

I use this pattern quite a lot.
currently, I'm doing this:

    var index = vm.mappedIndexof(data);
    if(index < 0) { 
         vm.push(ko.maping.fromJS(data));
    } else {
        ko.mapping.fromJS(data, vm()[index]);
    }
@RoyJacobs
Collaborator

The reason the mapping plugin does not do this, is that there is no clean way to signal deletions.

@luv2code

I think it would be alright to not be expected to support deletions this way. I mean, there really isn't a clean way to do it. So, one might be expected to explicitly call a mappedRemove(key).

but I can dig it if you don't want to add it to the library.

@RoyJacobs
Collaborator
@luv2code

turn it on like this?

var vm = ko.mapping.fromJS([], { arrayUpdate: true, arrayInsert:true });
@RoyJacobs
Collaborator
@luv2code

I gave this a shot; but I'm out of time. the updateViewModel function is hard to get my mind around. I kept breaking other unit tests without actually getting my change to work. I strongly feel that the function is too large and needs to be refactored into smaller chunks.

I'm giving up for now. I might come back to it later.

@RoyJacobs
Collaborator

Fair enough, development of the plugin has been fairly, shall we say, iterative :) So there is definitely a lot to be gained by cleaning it up. Sadly, with limited time on my side this has fallen by the wayside.

By the way, if you have any suggestions on restructuring the code and so on, by all means let me know. Good suggestions are always welcome!

@RoyJacobs RoyJacobs closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.