What would be considered a good way of handling lots of custom bindings with the possibility that the binding is not present?
Say my html expression binds to image_url as below.
<span title="Company Logo" data-bind="image_url: company_banner"></span>
However there is every possibility that the image_url binding is not available.
In that case scenario, I'd just like to return a string value of company_banner.
Normally one would add a custom handler like below but if that handler is not available can we return some generic feedback?
ko.bindingHandlers.buttonLabel = {//update etc}
In our case the design may be ahead of the code, so we don't want ko to grumble.
For this scenario, I would look at using a custom binding provider. Here is an article describing the functionality: http://www.knockmeout.net/2011/09/ko-13-preview-part-2-custom-binding.html.
So, I would create a custom binding provider that is a wrapper to the real binding provider. Once the bindings are parsed, then we can inspect them to see if they exist in ko.bindingHandlers
. If one does not, then we can add a text binding with its value.
It might look like:
ko.lenientBindingProvider = function() {
var realBindingProvider = new ko.bindingProvider();
this.nodeHasBindings = realBindingProvider.nodeHasBindings;
this.getBindings = function(node, bindingContext) {
//parse the bindings with the real binding provider
var result = realBindingProvider.getBindings(node, bindingContext);
//inspect the returned bindings
for (var binding in result) {
if (result.hasOwnProperty(binding) && binding !== "_ko_property_writers" && !ko.bindingHandlers[binding]) {
//add a text binding with whatever the missing binding was bound against
result.text = result[binding];
}
}
return result;
};
};
ko.bindingProvider.instance = new ko.lenientBindingProvider();
Here is a sample: http://jsfiddle.net/rniemeyer/mMQKY/