Reputation: 19742
So I want to create a shortcut for the template binding like this:
ko.bindingHandlers.shortcut = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var data = valueAccessor();
var nextValueAccessor = function () {
return { name: 'someTemplate', data: data };
};
ko.bindingHandlers.template.init.call(this, element, nextValueAccessor, allBindings, viewModel, bindingContext);
}
}
HTML:
<div data-bind="shortcut: 'Hey!'"></div>
<script type="text/html" id="someTemplate">
<div data-bind="text: $data"></div>
</script>
The "someTemplate" template is defined. It just doesn't work without saying anything. What am I doing wrong here?
Upvotes: 0
Views: 540
Reputation: 114792
Your issue is essentially that you are not calling the update
function of the template binding. You may find it easier to use a slightly different approach to wrap the binding though, so that you only have to use the init
function:
ko.bindingHandlers.shortcut = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
ko.applyBindingAccessorsToNode(element, {
template: function() {
return {
name: 'someTemplate',
data: valueAccessor()
};
}
}, bindingContext)
return { controlsDescendantBindings: true };
}
};
Sample: http://jsfiddle.net/rniemeyer/RXu9t/
If you are still using KO 2.x, then you would want to use ko.applyBindingsToNode
instead like:
ko.applyBindingsToNode(element, {
template: {
name: 'someTemplate',
data: valueAccessor()
}
}, bindingContext);
Sample: http://jsfiddle.net/rniemeyer/79yG8/
Upvotes: 5