Domanda

I have an issue trying to update an item as part of an observableArray using the mapping plugin.

I have the following code

accounts.list = ko.mapping.fromJS(@(Html.Raw(Model.AccountsJSON)));

I have this bound to a table using

<tbody data-bind="foreach: list"> ... </tbody>

This all works correctly, I then have the following function

$('#datatable').delegate(".cancelLock", "click", function() {
        var item = ko.contextFor(this).$data;
        var param = {AccountNumber : item.AccountNumber()}
        $.post('@Url.Action("cancellock","accounts")',param,function(result){
            ko.mapping.fromJSON(result,item);
            if(accounts.lockeditem() == item){
                accounts.lockeditem(0);
            }
        });
    });

the line ko.mapping.fromJSON(result,item); causes no errors, and the function continues, however it does not cause the observable to update.

I've tried changing the code to ko.mapping.fromJSON(result,accounts.list); (and updating my controller to return the full list) and this works correctly - the problem being that I don't want to update the entire table, I "simply" want to revert 'item' back to it's original state.

I've also tried using item.Updated(result.Updated); (where updated is one of the properties of the object) and this works as expected however I'd rather not manually call this on every property unless I have to.

is it possible to use ko.mapping.fromJSON(result,item); (or some variation of)? Am I doing something stupidly wrong?

Thanks in advance.

È stato utile?

Soluzione

Unless I misunderstood your intention, you can do this using a variation of ko.mapping.fromJS (or fromJSON) that's mentioned in the mapping docs under "Specifying the update target". So I think you want this:

ko.mapping.fromJSON(result, {}, item); 

Here's a fiddle: http://jsfiddle.net/kR4jc/

Altri suggerimenti

I updated the fiddle to reference rawgithub.com and the latest knockout.js file..

http://jsfiddle.net/kR4jc/5/

https://rawgithub.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js
http://knockoutjs.com/downloads/knockout-2.2.1.js

This post also helped me https://github.com/SteveSanderson/knockout.mapping/issues/41

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top