Reputation: 202
I have ViewModel like this:
function ViewModel() {
var self = this;
self.Tab = function (id, name, text, selected) {
var tab = this;
tab.id = ko.observable(id);
tab.name = ko.observable(name);
tab.text = ko.observable(text);
return tab;
};
self.selectedTab = ko.observable(1);
self.tabs = new Array();
self.tabs.push(new self.Tab(1, 'Tab 1', 'Tab 1 Content'));
self.tabs.push(new self.Tab(2, 'Tab 2', 'Tab 2 Content'));
self.tabs.push(new self.Tab(3, 'Tab 3', 'Tab 3 Content'));
self.tabs.push(new self.Tab(4, 'Tab 4', 'Tab 4 Content'));
return self;
}
ko.applyBindings(new ViewModel(), document.getElementById("TabDiv"));
And related HTML is as follows:
<div id="TabDiv">
<div id="tabs" data-bind="foreach: tabs">
<div class="tab" data-bind="css: {selected: $parent.selectedTab() == id()}, text: name, click: $parent.selectedTab.bind($parent, id())">
</div>
</div>
<div id="tabContent" data-bind="foreach: tabs">
<div data-bind="if: $parent.selectedTab() == id()">
<span data-bind="text: text"></span>
</div>
</div>
</div>
Now,i have another ViewModel as Follows:
var ProjectViewModel = {
........
AddEmployee: function (data, event) {
$('.chkList').each(function () {
//Here i want to generate tab
});
}
};
The checkbox list is binded to one of the observable array of ProjectViewModel which is all working fine. What i am trying to do is,on click of the checkbox inside checkbox list, generate a Tab(similar to Jquery UI Tab).
You can see 4 tab values inserted statically which is working perfectly. I am getting tab as expected. But i am not able to push values which i get inside ProjectViewModel's AddEmployee function into tabs array in ViewModel. I don't know how to process self.tabs.push(new self.Tab(.....)); outside the ViewModel.
Any help is greatly appreciated.
Upvotes: 1
Views: 963
Reputation: 49095
You can use ko.dataFor()
to access the view-model:
AddEmployee: function (data, event) {
var vm = ko.dataFor(document.getElementById("TabDiv"));
vm.tabs.push(new vm.Tab(5, 'New Tab', 'New Tab Content'));
}
Alternatively, you can expose the view-model to the global scope then access it everywhere:
window.tabsVM = new ViewModel();
ko.applyBindings(window.tabsVM, document.getElementById("TabDiv"));
Then:
AddEmployee: function (data, event) {
var vm = window.tabsVM;
vm.tabs.push(new vm.Tab(5, 'New Tab', 'New Tab Content'));
}
Also, you'll have to change your tabs
array into an observable-array if you want your changes to update the DOM automatically:
self.tabs = ko.observableArray();
Upvotes: 1