I have a simple list view which displays items, with the help of Knockout. A set of 'Things' are hard coded into an array and Knockout lists them at page load. It works fine so far.
Now, I wish to add a new function: newFunc(). A new item will be created in the function with a property, but without a name. The item can be added to the list later, if the user wishes. A name can be given to the item by the user then.
Q: In this situation, how can I (or can I) use the constructor function 'Item' to create a new item, in the new function? The 'Item' function requires an argument 'item', yet in the new function, I cannot pass an argument, since the new item is being created and a name is not given. How should I think and code differently to achieve the functionality described?
Any help and tips would be appreciated.
// HTML //
<ul data-bind='foreach: itemList'>
<li data-bind='text: name'></li>
</ul>
// Script //
var Things = [
{ name: 'name1', property: 'prop1' },
{ name: 'name2', property: 'prop2' },
...
];
var Item = function(item) {
this.name = item.name;
this.property = item.property;
};
// The new function in Question
var aNewItem;
newFunc = function() {
// I'd like to create an 'Item' with a given property, but w/o a name.
aNewItem = new Item(); // ???
aNewItem.property = 'propertyN'; // **Edit**: also a variable set by user or callback.
};
var viewModel = function {
self = this;
self.itemList = ko.observableArray();
Things.forEach(function(item) {
self.itemList.push(new Item(item));
});
};
ko.applyBindings(new viewModel());