我想我會用一個新的解決方案更新這個問題,我開始使用。我以前一直使用RP Niemeyer的小提琴http://jsfiddle.net/rniemeyer/dsKbH/作爲動態添加/刪除綁定到KO observableArray的jQuery UI選項卡的基礎。
在過去的幾個月裏,我碰到了與我的應用相關的一些問題:A)setTimeout()推遲,B)每次觸發更新時銷燬和重新創建選項卡小部件。所以我想出了一個不同的方法來避免這些問題,恕我直言,這是一種更優雅的技術。
http://jsfiddle.net/LatencyMachine/XJPJZ/
的核心思想是介紹一個非常簡單的自定義綁定名爲「一個tabpanel」和相應的部件,綁定到你的標籤面板內容的div。由於KO基於您的observableArray創建和刪除這些div,tabPanel綁定會確保使用它的「刷新」方法更新jQueryUI.tabs。我認爲這比試圖讓標籤在容器元素的綁定中更新(並在適當的時候)更順暢。從小提琴
相關代碼
/**
KO Binding handler for a tabPanel div. Use this on divs that can appear/disappear and/or have their id change
depending upon an observable, usually an observableArray.
*/
ko.bindingHandlers.tabPanel = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).tabPanel(ko.toJS(valueAccessor()));
}
};
/**
This widget facilitates jQuery UI tabs that appear and disappear dynamically, usually as a result of MVVM like Knockout
Whenever this widget is created, the containing jQuery UI 'tabs' widget is refreshed so that it picks up the new tab
or drops the removed one.
This also facilitates dealing with id rename 'ripple' that occurs whenever a tab is removed due to the splice of an
observable array.
*/
$.widget("bw.tabPanel", {
options: {
id: null
},
_create: function() {
this.element.hide();
this.tabsElement = this.element.closest(".ui-tabs");
if(this.options.id) {
this.element.attr({id: this.options.id});
}
this.refreshTabs();
},
_destroy: function() {
if(this.options.id) {
this.element.attr({id: ""});
}
this.refreshTabs();
},
_setOption: function(key, value) {
var previousValue = this.options[key];
if(previousValue == value) return;
this.options[key] = value;
switch(key) {
case "id":
this.element.attr({id: this.options.id});
this.refreshTabs();
break;
}
},
/**
Invoke refresh on the parent tab to let it know that something has changed.
This also preserves the active index by setting it back to what it was before the refresh, which
may correspond to a different tab after the refresh.
*/
refreshTabs: function() {
var previousActiveIndex = this.tabsElement.tabs("option", "active");
this.tabsElement.tabs("refresh");
this.tabsElement.tabs("option", "active", previousActiveIndex);
}
});