I’m using knockoutjs version 2.2.0 and have the following situation:
Javasript Code
Here is my javascript code with 3 models: ‘Tab1’, ‘Tab2’ and ‘viewModel’
var CustomExport = {
Tab1: function () {
this.tab1Array = ko.observableArray([
{name: "Tab1 Item1"},
{name: "Tab1 Item2"},
{name: "Tab1 Item3"}
]);
},
Tab2: function () {
this.tab2Array = ko.observableArray([
{name: "Tab2 Item1"},
{name: "Tab2 Item2"},
{name: "Tab2 Item3"}
]);
},
viewModel: function () {
this.myTab1 = new CustomExport.Tab1();
this.myTab2 = new CustomExport.Tab2();
this.grabData = function(){
alert(ko.toJS(CustomExport.viewModel));
};
}
}
ko.applyBindings(new CustomExport.viewModel());
So, in general I have 2 models and I want to grab all data from those models into one “viewModel” model as a json object, the grabData function should alert me the models data.
Here is my HTML Code
<div data-bind="with: myTab1">
<ul data-bind="template: {name: 'tabTmpl', foreach: tab1Array}"></ul>
</div>
<br/>
<div>------------------------------------------</div>
<br/>
<div data-bind="with: myTab2">
<ul data-bind="template: {name: 'tabTmpl', foreach: tab2Array}"></ul>
</div>
<br/>
<input type="button" data-bind="click: grabData" value="Grab all data from Models" />
<script id="tabTmpl" type="text/html">
<li>
<div data-bind="text: name"></div>
</li>
</script>
The issue is the following:
Clicking on the ‘Grab all data from the models‘ button I should get an alert which must contains data from 2 models (‘Tab1’, ‘Tab2’) as a json object, but currently I got the following alert message:
function () {
this.myTab1 = new CustomExport.Tab1();
this.myTab2 = new CustomExport.Tab2();
this.grabData = function(){
alert(ko.toJS(CustomExport.viewModel));
};
}
Also, I have created it in my jsFiddle Click here to see an example
Any idea what am I doing wrong?
You should use
thisinstead ofCustomExport.viewModel:But it is better to create closure for
this: