这里的秘密是http://knockoutjs.com/documentation/custom-bindings.html
ko.bindingHandlers.myCustomBinding = {
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
if (bindingContext.$data.init) bindingContext.$data.init(element, valueAccessor, allBindings, viewModel, bindingContext);
},
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.
if (bindingContext.$data.update) bindingContext.$data.update(element, valueAccessor, allBindings, viewModel, bindingContext);
}
};
所以在我的组件模板中我做了类似的事情
<div class="row-fluid" data-bind="myCustomBinding: 'someValue'">
在组件 viewModel 上我只是实现了初始化和/或更新,例如:
constructor.prototype.init = function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// All the buttons in the buttons group need the same name,
// but they all need distinct ids. We use timestamps because
// as components, the names and ids should be distinct across
// multiple instances of each component.
var timeStamp = new Date().getTime();
$('input:radio').attr('name', timeStamp).button();
$('input:radio:eq(0)').attr('id', timeStamp+1);
$('input:radio:eq(1)').attr('id', timeStamp+2);
$('input:radio:eq(2)').attr('id', timeStamp+3);
// Initialize the number-picker
$('input[name="number-picker"]').TouchSpin();
};
指出这个非常有用的案例可以改进 Knockout 文档。此外,这是一个非常有用的绑定,应该有一个标准的 'init' 和 'update' 绑定,例如
<div data-bind="init: 'someValue'">