2013-02-14 48 views
1

結合我使用淘汰賽ATTR用於數據綁定的屬性,如:問題使用attr在淘汰賽

<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }"> 
</div> 

現在我想那是什麼不是我不想,如果任何可觀察到varibale即Fire and Age爲空或空添加一個空的屬性名稱。因此應用後,如果假設Age結合是空的,比我不希望我的標記是:

<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }" data-age data-fire="Yes"> 
</div> 

相反,我想刪除數據時代,並希望這種清潔標記:

<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }" data-fire="Yes"> 
</div> 

是否有任何在knockout.js中實現這一點的方法?

+0

順便說一下,空屬性的問題是什麼? – 2013-02-14 10:57:38

+0

它不必要地增加標記大小 – gaurav 2013-02-14 10:59:40

+0

自定義綁定可能是您想要的。更新了答案。 – 2013-02-14 11:06:05

回答

1

可以使用custom binding這個控制自己:

<div data-bind="addAttributes : { 'data-fire': Fire, 'data-age': Age }"></div> 

然後有一個處理程序:

ko.bindingHandlers.yourBindingName = { 
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     // This will be called when the binding is first applied to an element 
     // Set up any initial state, event handlers, etc. here 
    }, 
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     // This will be called once when the binding is first applied to an element, 
     // and again whenever the associated observable changes value. 
     // Update the DOM element based on the supplied values here. 
    } 
}; 

在這些方法中,你可以檢查值和手動(使用jQuery添加屬性,例如)只有當這些值不是空白時。

+0

謝謝指出,但那是隻是一個錯字,我更新了問題 – gaurav 2013-02-14 10:57:21

+0

是的,剛纔看到,當我輸入我的答案時,有很多編輯!爲什麼空屬性是一個問題? – 2013-02-14 10:58:36

+0

+1爲自定義綁定思想作爲解決方案 – gaurav 2013-02-14 11:09:46