1

I'm using a combination of Knockout.js + the Knockout mapping plugin + jQuery in a rich web client that consumes JSON from a RESTful API.

I need some guidance on how to deal with null values in my view model. Here's my scenario and the problem I'm running into:

Most of the data members returned by the REST API are nullable. To account for this, I'm passing to the mapping plugin a sample of JSON with null values:

um.jsonMaps.campaign = {
    "priority": null,
    "recipientListId": null,
    "autoPrepare": null,
    "timeToSend": null
}

I do the initial binding like this:

this.model = ko.mapping.fromJS(um.jsonMaps.campaign);

Here's some data from an API call:

var data= {
    "priority": 95,
    "recipientListId": "a2aac72a-59f6-45da-a636-a48cc2b20137",
    "autoPrepare": false,
    "timeToSend": null
}

...which is bound like this:

ko.mapping.fromJS(data, this.viewModel.model);

The problem is that if users modify or touch any of the UI elements bound to this data, they implicitly turn the data member in the model into a quoted string literal. So, the integer 95 becomes "95" if the user adds some text and deletes it. And if a value that was null from the API is touched in the UI, it becomes "" (e.g. the empty string).

I need ints and nulls to remain as ints and nulls after editing.

4

2 に答える 2