Knockout JS - How to return empty strings for observable fields

主宰稳场 提交于 2020-01-06 13:02:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!