Christian Mikkelsen
Christian Mikkelsen

Reputation: 1701

KnockoutJS.Mapping.FromJS - Observable array - Remove not working

With the following code I would expect that any new objects are added to the viewModel and any delete objects are removed, whenever ko.mapping.fromJS(response.results, viewModel); is called. But it only adds new object and the old one stick around in the html:

var viewModel = ko.mapping.fromJS([],
{
        key: function(data) {
            return ko.utils.unwrapObservable(data.Id);
        },
        create: function (options) {
            return new newConfigModel(options.data);
        }
});

var newDispModel = function (data) {
        ko.mapping.fromJS(data, {}, this);

        this.DisplayTitle = ko.dependentObservable(function() { return GetDisplayTitle(this); }.bind(this));
        this.StatusClass = ko.dependentObservable(function () { return GetStatusClass(this); }.bind(this));

        this.FeedIndexShadow = "";
        this.FeedIndex = ko.dependentObservable(function() { return GetNewFeedIndex(this); }.bind(this));
    };

$(document).ready(function () {

    function loadConfigurations() {
        var url = "/Home/GetItems/";
        $.ajax({
            url: url,
            success: function(response) {

                if (response.success) 
                {
                    ko.mapping.fromJS(response.results, viewModel);

.... and the last part ....

<div class="container" id="feeds"  data-bind="foreach: viewModel">

    <div data-bind="attr: { 'class': StatusClass, 'id': FeedIndex }" style="display: none">
        <div class="configRow">
             <h2 class="title" data-bind="text: DisplayTitle"/>
        </div>
    </div>
</div>

What am I missing? Has it something todo with the key, must I simply manually remove "dead" objects from the observable somehow or have I completely misunderstod the functions of ObservableArrays?

Upvotes: 0

Views: 2343

Answers (1)

John Earles
John Earles

Reputation: 7194

Here is a JSFiddle that shows the interaction:

NOTE: The 'update' entry in the mapping was just so I could log to the console... it isn't needed unless you need to customize how updates happen.

http://jsfiddle.net/jearles/wgZ59/49/

Hit 'Load Matrix' and it will display:

12
23
34

Click 'Change' and it will reload the matrix:

24
45

Looking at the console messages I post you see:

Creating 1
Updating 1
Creating 2
Updating 2
Creating 3
Updating 3
Updating 2
Creating 4
Updating 4

Which seems to confirm the actions are occurring as expected.

12 - Is deleted
23 - Is changed to 24
34 - Is deleted
45 - Is added

--

The 'key' entry helps the mapping plugin determine which entries are new or existing by designating a particular property as being the "key"; otherwise the entire object is compared for equality.

http://knockoutjs.com/documentation/plugins-mapping.html

Upvotes: 1

Related Questions