Reapply bindings in knockout

三世轮回 提交于 2020-01-11 04:52:10

问题


I basically want to reapply bindings on the same page for the different objects, but there is strange behavior. After I reapply the binding, the list of items is lost.

Please see here: http://jsfiddle.net/baio/9UcUs/5/

What to do?


回答1:


The short answer is that it's not supported. The long answer is that there are some ways around it. One way is to call cleanNode before applyBindings, but this doesn't clear event handlers. Another way is to wrap your view model in an observable and then update that observable to reapply bindings; this works much better, but still has a slight problem (see below).

Here is your example using the observable view model method: http://jsfiddle.net/mbest/9UcUs/9/

The only problem I've found with using an observable view model is that event handlers are not completely updated with the new view model. They will call the correct function in the new view model, but the this and data values will be for the original view model.

Edit:

Knockout 3.0 (currently scheduled for release this month) fully supports observable view models. There still could be issues with custom bindings, but hopefully all this will be documented soon.




回答2:


you can bind the same viewmodel to different elements, you need specify the element you want to apply your binding to.

ko.applyBindings(vm, $('#yourul'));

ko.applyBindings(vm, $('#div'));



回答3:


Doing:

ko.applyBindings(viewModel, $('#somejQObj')[0]);

Works as stated in the comments of @fengd's answer. Currently have a table that is populated by a foreach statement, that has expandable rows that each one has a dynamically added sub-table that is also populated by a foreach statement. After each sub-table is dynamically inserted doing the above sets the bindings for the sub-table and populates the data.



来源:https://stackoverflow.com/questions/12314736/reapply-bindings-in-knockout

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