In short: I'm looking for the component-equivalent of binding preprocessing.
I am trying to encapsulate complex bindings such as
<button data-bind="openModalOnClick: {template: '...', action: '...'}, css: {...}">
delete all the things
</button>
in a custom element such as
<confirmation-button>
delete all the things
</confirmation-button>
In order to do so, I want to attach behaviour to the custom element directly by adding bindings to it on the fly.
I am aware that I can have my component insert the button as a template, but the resulting markup
<confirmation-button>
<button data-bind="openModalOnClick: {template: '...', action: '...'}, css: {...}">
delete all the things
</button>
</confirmation-button>
would be redundant.
Ideally, I could use the component registration to add the required bindings dynamically to the custom element. However, (ab)using createViewModel
for this does not seem to work:
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>
Is it possible to add dynamic bindings to custom elements themselves in some fashion?