The custom binding is not the solution to your problem. Knockout will bind everything it encounters in the DOM therefore whichever type of object you initialise your value with, the other one will fail. I've implemented something similar where an observable in my view-model stores multiple 'types' of object, which you will need 'type-specific' portions of UI bound to each. This is how i tackled the problem:
Remove all instances of, if: type() == '<type>'
and implement each piece of HTML as a template.
Now refactor that decision making process. Use a computed observable to decide which template is shown based on the type()
. Something like this...
function ViewModel(){
var self = this;
self.type = ko.observable();
self.value = ko.observable();
self.currentValueTemplate = ko.computed(function(){
switch(self.type()) {
case 'string':
return 'stringTemplate';
case 'duration':
return 'durationTemplate';
default:
throw 'invalid type';
}
});
Now simply add a template placeholder...
<!-- ko template: { name: currentValueTemplate, data: value } -->
<!-- /ko -->
You may want to adapt this to fit the specifics of your application, but it is a tidier approach and will scale much better should you want to store an increasing variety of object types.