Is it possible to create knockout bindings from javascript alone, i.e. without writing custom html attributes?

I'm very much stuck with our existing markup and can't add data-bind etc. that knockout.js relies on (html is generated programmatically and there is no access to the rendering pipeline, please assume I've exhausted my options in trying :)

One idea that I'm tentatively pursuing is adding data-bind attributes at runtime prior to calling ko.applyBindings. Is there a preferred approach? I'll also accept an alternative, sufficiently documented/popular/stable framework if it also implements bindings similar to knockout.js if/visible.

有帮助吗?

解决方案

Knockout 3.0 (which just around the corner and is in release candidate now) opens up a lot more ways to interact with the binding process, such as the ability to preprocess nodes and dynamically generate bindings. Take a look at Knockout.Punches to see some examples of what is possible. Between that and the things already mentioned like the unobtrusive and class binding providers, you should have no trouble working with whatever markup you're stuck with.

It may also be worth pointing out knockout has an applyBindingsToNode function which takes in a JSON object of the bindings if you want full control, though that does not apply bindings to descendant elements.

其他提示

Knockout allow us to create custom binding provider, I find out there is several libs that help you to do it

You can find them here:

One that don't use DOM at all:

https://github.com/tobio/knockout.unobtrusivebindingprovider

One that use another approach :

https://github.com/rniemeyer/knockout-classBindingProvider

At last resort if none of them suit your needs, you can with jQuery modify the DOM then call the binding on it...

Look at the "Unobtrusive event handling" section in the Knockout documentation under "Further techniques".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top