JSFiddle - React, Tailwind, and code Playground
HTML
<button data-bind="click: switchToFirst">Select 1st tab</button>
<button data-bind="click: switchToSecond">Select 2nd tab</button>
<div data-bind="text: selectedTab().content"></div>
<div style="height: 30px"></div>
<button data-bind="click: selectItem">Select some item</button>
Current id: <span data-bind="text: itemId"></span>
JavaScript
var asyncComputed = function (evaluator, owner, options) {
var result = ko.observable(),
updateTrigger = ko.observable().extend({ notify: 'always' }),
updateComputed,
updateSubscription;
result.refresh = function () {
updateTrigger.valueHasMutated();
};
result.active = (options && typeof options.activeWhen == "function") ? options.activeWhen : function () { return true };
updateComputed = ko.pureComputed(function () {
updateTrigger();
result(evaluator.call(owner)); // let's pretend it's always sync (for simplicity)
});
ko.computed(function () {
var isActive = result.active();
if (isActive && !updateSubscription) {
updateSubscription = updateComputed.subscribe(function () {});
} else if (updateSubscription && !isActive) {
updateSubscription.dispose();
updateSubscription = undefined;
}
});
return result;
};
var viewModel = new function(){
var self = this;
self.selectedTab = ko.observable();
self.itemId = ko.observable(0);
self.selectItem = function(){
self.itemId(self.itemId() + 1);
};
self.firstTab = new function(){
var tab = this;
tab.content = asyncComputed(function(){
alert("loading 1st tab content..."); return "1st tab content for id = " + this.itemId();
}, self, { activeWhen : function(){ return self.selectedTab() === tab }})
};
self.secondTab = new function(){
var tab = this;
tab.content = asyncComputed(function(){
alert("loading 2nd tab content..."); return "2nd tab content for id = " + this.itemId();
}, self, { activeWhen : function(){ return self.selectedTab() === tab }})
};
self.switchToFirst = function(tab){
self.selectedTab(self.firstTab);
};
self.switchToSecond = function(tab){
self.selectedTab(self.secondTab);
};
...