Skip to content Skip to sidebar Skip to footer

Referencing Properties Of Object Constructor Outside View Model In Knockout

So, I'm not entirely sure how to phrase this question as it's sort of two in one. I'm having a weird issue where I have an object constructor to create new 'projects' from an HTML

Solution 1:

Your code is setting title and priority properties on the object created by new Project, but then later you're expecting to see those properties on Project itself. It doesn't have them; Project is the function, not the object created by new Project. So Project.title and Project.priority will give you undefined (and not an observable, and so not useful targets for the value binding).

Instead, have an "editing" Projectinstance that you use, binding the value of the inputs to the editing' instances title and priority, and then in newProject grab that instance and replace it with a new, fresh one.

Roughly speaking, in ProjectViewModel's constructor:

this.editing = ko.observable(new Project());

Update Project to default title and priority:

functionProject(title, priority) {
  this.title = ko.observable(title || "");
  this.priority = ko.observable(priority || "Medium");
}

And in the bindings:

<input id='pTitle' data-bind='value: editing().title' />
<select id='pPriority' data-bind='options: priorityOptions, value: editing().priority'></select>

And in newProject:

var np = this.editing();
this.editing(new Project());

Then use np (instead of another new Project) when adding to the array.

Here's a simplified example:

functionProject(title, priority) {
  this.title = ko.observable(title || "");
  this.priority = ko.observable(priority || "Medium");
}


functionProjectViewModel() {
  var self = this;
  this.priorityOptions = ko.observableArray(["High", "Medium", "Low"]);
  this.projects = ko.observableArray();
  this.editing = ko.observable(newProject());
  this.addProject = function() {
    this.projects.push(this.editing());
    this.editing(newProject());
  };
}

ko.applyBindings(newProjectViewModel(), document.body);
<div><div><label>
      Title:
      <inputtype="text"data-bind="value: editing().title, valueUpdate: 'input'"></label></div><div><label>
      Priority:
      <selectdata-bind='options: priorityOptions, value: editing().priority'></select></label></div><div><buttontype="button"data-bind="click: addProject, enable: editing().title">Add Project</button></div><hr><div>Projects:</div><divdata-bind="foreach: projects"><div><spandata-bind="text: title"></span>
      (<spandata-bind="text: priority"></span>)
    </div></div></div><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Post a Comment for "Referencing Properties Of Object Constructor Outside View Model In Knockout"