How to use knockout mapping?

2019-08-17 22:20发布

问题:

I have applied bindings to the following view model

var groupDeleteViewModel = {
        group: { Id: ko.observable(), Name: ko.observable(), Members: ko.observableArray() },
        load: function (item) {
            debugger

        },
        remove: function (item) {
            groupDeleteViewModel.group.Id(item.Id());
            groupDeleteViewModel.group.Name(item.Name());
            groupDeleteViewModel.group.Members(item.Members());
            $("#groupDelete").show();
        },
        cancel: function () {
            $("#groupDelete").hide();
        }
    }

the remove function loads the view with the data that has been passed in item to the remove function.

<div id="groupDelete" class="pop-window filter-view">
    <h2>
        Delete Group
    </h2>
    <table>
        <tr>
            <th>
                Name
            </th>
            <td>
                <span data-bind="text:group.Name" />
            </td>
        </tr>
        <!--ko foreach: group.Members-->
        <tr>
            <th>
            </th>
            <td>
                <div data-bind="text:Name" class="grey-border">
                </div>
            </td>
            <td>
            </td>
        </tr>
        <!--/ko-->
    </table>
    <span class="centeralign">
        <input type="button" value="Delete" data-bind="click: remove" class="delete" />
        <input type="button" value="Cancel" data-bind="click: cancel" />
    </span>
</div>

I don't want to keep mapping each element of item to each element of groupDeleteViewmodel.group. I have done it at a lot of other places also in the code which has made the code really messy. I want to use the ko.mapping plugin to do the same thing.

Till now what I have tried is -

remove:function (item){
            var data = ko.mapping.toJS(item);
            ko.mapping.fromJS(data, groupDeleteViewModel.group);
            $("#groupDelete").show();
}

But this just does not work. i really don't know why. It should have worked ideally. Can someone tell what is the right way of using ko.mapping in such a case?

Thanks.

回答1:

The mapping plugin is looking for mapping data already present in groupDeleteViewModel.group, but it doesn't find it, because you didn't initialize groupDeleteViewModel.group using the mapping plugin. So instead of initializing group like you did:

group: { Id: ko.observable(), Name: ko.observable(), Members: ko.observableArray() }

initialize it using the mapping plugin:

group: ko.mapping.fromJS({ Id: undefined, Name: undefined, Members: [] })

And this is me fiddling around with your code: fiddle