How to bind knockout checkbox to a material design lite?

て烟熏妆下的殇ゞ 提交于 2019-12-06 04:08:11

The problem here is that material design runs a function on page load to bind event handlers and functionality to certain DOM elements (like the checkbox in your case).

Because knockout essentially needs to run (or will redraw when dependencies change) the elements you bind functionality to. In your case, the foreach can/will only run after knockout has been intialized, which is typically done on DOM ready. Hence, Material won't have had access to that element when it runs it's bindings initially.

You need to have a Custom Binding to run the Material "logic" on the readiness of the element. The process is dead simple.

Pseudo-code:

  1. Create a custom binding called whatever you'd like.
  2. In the custom binding init method, pass the element knockout gives you into the Material function that will attach the required event handlers.

Hopefully that helps you!

EDIT: From the Material Design lite webpage

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

Knowing this, in your Custom Binding you need to pass the element knockout gives you, to the aforementioned handler, like: componentHandler.upgradeElement(element)

EDIT EDIT: The code

ko.bindingHandlers.SomeBinding = {
    init: function(element) {
        if(!(typeof(componentHandler) == 'undefined')){
            componentHandler.upgradeElement(element);
        }
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!