简而言之:我正在寻找与绑定预处理等效的组件。
我正在尝试封装复杂的绑定,例如
<button data-bind="openModalOnClick: {template: '...', action: '...'}, css: {...}">
delete all the things
</button>
在自定义元素中,例如
<confirmation-button>
delete all the things
</confirmation-button>
为此,我想通过动态添加绑定来直接将行为附加到自定义元素。
我知道我可以让我的组件将按钮作为模板插入,但生成的标记
<confirmation-button>
<button data-bind="openModalOnClick: {template: '...', action: '...'}, css: {...}">
delete all the things
</button>
</confirmation-button>
将是多余的。
理想情况下,我可以使用组件注册将所需的绑定动态添加到自定义元素。但是,(ab)createViewModel
为此使用似乎不起作用:
ko.components.register('confirmation-button', {
viewModel: {
createViewModel: function createViewModel(params, componentInfo) {
var Vm;
$(componentInfo.element).attr('data-bind', 'click: function() { confirm("Are you sure"); }');
Vm = function Vm(params) { };
return new Vm(params);
}
},
template: '<!-- ko template: { nodes: $componentTemplateNodes } --><!-- /ko -->'
});
confirmation-button {
border: 1px solid black;
padding: 1rem;
cursor: pointer;
}
<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<confirmation-button>do stuff</confirmation-button>
是否可以以某种方式将动态绑定添加到自定义元素本身?