问题
Im building a CRUD system where users can add, delete and edit data from a simple table. I have a modal form that is used to show additional details and also adding new incidents. Currently the modal form loads correctly for editing but has issues when trying to add a new incident.
After some debuging it seems that the issue comes from this line:
self.currentIncident(null);
This breaks my modal form because my observable is coming back null (obviously). I was hoping that it would return something like the following:
"ID": "",
"Description": "",
"Incident": ""
I believe this is why my modal is crashing since my modal is confused with the return. Would someone know of an easy method to return empty strings?
self.AddNewIncident = function() {
var id = this.ID;
self.showModal(true);
self.currentIncident(null);
};
Here is jsfiddle: http://jsfiddle.net/rqwku4kb/12/
回答1:
Put {} instead of null like this:
self.currentIncident({});
Check Fiddle
回答2:
You could declare Incident in this way:
function Incident(data) {
var self = this;
self.ID = -1;
self.Description = ko.observable();
self.Incident = ko.observable();
if (!data) return;
// initialize with 'data'
self.ID = data.ID;
self.Description(data.Description);
self.Incident(data.Incident);
}
and then
self.currentIncident(new Incident());
来源:https://stackoverflow.com/questions/34258074/knockout-js-how-to-return-empty-strings-for-observable-fields