Knockout js lots of custom bindings

做~自己de王妃 提交于 2019-12-22 10:38:00

问题


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.


回答1:


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/



来源:https://stackoverflow.com/questions/8927909/knockout-js-lots-of-custom-bindings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!