除了 Knockout 內建的綁定型別(value、text、visible 等),你也可以自己寫綁定。本文說明如何註冊自定義 binding handler,以及兩個回呼各自的職責。
ko.bindingHandlers.yourBindingName = {
init: function(element, valueAccessor, allBindings, 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, allBindings, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever any observables/computeds that are accessed change
// Update the DOM element based on the supplied values here.
}
};
之後就能在任意 DOM 元素上使用:
<div data-bind="yourBindingName: someValue"></div>
注意:init 與 update 可以只提供其中一個,視需求而定。
顧名思義,當綁定所依賴的 observable 變動時,KO 會自動呼叫 update。它的五個參數:
element:套用此綁定的 DOM 元素。
valueAccessor:呼叫 valueAccessor() 可取得目前綁定的 model 屬性值;用 ko.unwrap(valueAccessor()) 可以更省事地同時處理 observable 與普通值。
allBindings:綁定到此元素上的所有 model 屬性,例如 allBindings.get('name') 取值(不存在回傳 undefined),或 allBindings.has('name') 判斷是否存在。
viewModel:在 KO 3.x 中已棄用,請改用 bindingContext.$data 或 $rawData。
bindingContext:綁定上下文,可用 $data、$parent、$parents 等取得資料。
舉個實例:想為 visible 綁定加上滑動動畫:
ko.bindingHandlers.slideVisible = {
update: function(element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
var valueUnwrapped = ko.unwrap(value);
// Grab some more data from another binding property
var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified
// Now manipulate the DOM element
if (valueUnwrapped == true)
$(element).slideDown(duration); // Make the element visible
else
$(element).slideUp(duration); // Make the element invisible
}
};
使用方式:
<div data-bind="slideVisible: giftWrap, slideDuration:600">You have selected the option</div>
<label><input type="checkbox" data-bind="checked: giftWrap" /> Gift wrap</label>
<script type="text/javascript">
var viewModel = {
giftWrap: ko.observable(true)
};
ko.applyBindings(viewModel);
</script>
KO 會為每個套用該綁定的元素呼叫一次 init,主要有兩個用途:設定元素的初始狀態,以及註冊事件處理器(例如點擊或修改時回寫 observable)。參數與 update 完全相同。
延續上例,如果希望首次顯示時不播放動畫、直接套用可見狀態,動畫只在使用者操作時才出現,可以這樣寫:
ko.bindingHandlers.slideVisible = {
init: function(element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
// Get the current value of the current property we're bound to
$(element).toggle(value); // jQuery will hide/show the element depending on whether "value" or true or false
},
update: function(element, valueAccessor, allBindings) {
// Leave as before
}
};
若 giftWrap 初始為 ko.observable(false),關聯的 DIV 在載入時就是隱藏狀態,之後點擊 checkbox 才會顯示。
update 負責把 model 的變化反映到 DOM;反過來,我們也可以在 init 裡監聽使用者操作,回寫 observable。這樣這個綁定就成了可讀可寫的:
ko.bindingHandlers.hasFocus = {
init: function(element, valueAccessor) {
$(element).focus(function() {
var value = valueAccessor();
value(true);
});
$(element).blur(function() {
var value = valueAccessor();
value(false);
});
},
update: function(element, valueAccessor) {
var value = valueAccessor();
if (ko.unwrap(value))
element.focus();
else
element.blur();
}
};
使用時就能直接讀寫元素的「焦點狀態」:
<p>Name: <input data-bind="hasFocus: editingName" /></p>
<!-- Showing that we can both read and write the focus state -->
<div data-bind="visible: editingName">You're editing the name</div>
<button data-bind="enable: !editingName(), click:function() { editingName(true) }">Edit name</button>
<script type="text/javascript">
var viewModel = {
editingName: ko.observable()
};
ko.applyBindings(viewModel);
</script>
掌握 init 與 update 的分工——前者負責「設定初始狀態與綁定事件」,後者負責「資料變動時更新畫面」——你就能把任何 DOM 操作都封裝成可重複使用的宣告式綁定。