I have javascript code block and html like below. The model object is a generic. It is defined at run time.
It can be like this.
var model = { "xId": ko.observable(0), "xName": ko.observable(null), "Type": ko.observable("x") };
/* var model = { "yId": ko.observable(0), "yName": ko.observable(null), "Type": ko.observable("y") };
var model = { "zId": ko.observable(0), "zName": ko.observable(null), "Type": ko.observable("z") }; */
var vm = function (data) {
ko.mapping.fromJS(data, {}, this);
};
var vm2 = function () {
var self = this;
self.New = ko.observable(null);
self.NewItem = function () {
console.log(model);
self.New(new vm(model));
};
};
var viewModel = new vm2();
ko.applyBindings(viewModel);
vm.prototype.Save = function () {
viewModel.New(null);
/*In here all of inputs must be cleared but How to :)*/
};
The newForm for first model.
<input type="button" data-bind="click: NewItem" value="Add" />
<div data-bind="with:New" id="newForm">
<input type="text" data-bind="value:xId" />
<input type="text" data-bind="value:xName" />
<input type="text" data-bind="value:Type" />
<input type="button" data-bind="click: Save" value="Save" />
</div>
I click the add button, then I tpye sometings to inputs, then I click the save button. The newForm is invisible. So far everything is ok. But I click the add button again, I had written values are still in the inputs. I can't clear the newForm after save.
EDIT:
public class Test{
public int TestId {get; set;}
public int TestName {get; set;}
}
public class Test2{
public int Test2Id {get; set;}
public int Test2Name {get; set;}
}
The coutn of entity classes is not clear.
My entity classes is converted json. the model is create by .net like this. My project have a master page and subpages. for test page :
var model = <%=ViewModelCreator.Create<Test>() %>;
for test2 page :
var model = <%=ViewModelCreator.Create<Test2>() %>;
edit: Your viewmodel is a bit strange, having that inner model that is a static reference to the same observables, the mapping plugin will reuse old observables when they find them. Why are you even mapping like that to a static defined collection of observables, why not just explicit declare your viewmodel?
Old answer Could do it?
for(var index in vm) {
if(ko.isObservable(vm[index])) {
vm[index](null);
}
}
edit: You could also create a special observable that is clearable