Knockout JS - How to return empty strings for obse

2019-09-05 16:39发布

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/

2条回答
萌系小妹纸
2楼-- · 2019-09-05 17:24

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());
查看更多
Root(大扎)
3楼-- · 2019-09-05 17:39

Put {} instead of null like this:

self.currentIncident({});

Check Fiddle

查看更多
登录 后发表回答