Knockoutjs: refresh bindings after populating select list

拟墨画扇 提交于 2020-01-15 07:39:31

问题


I feel like this must have been asked before, but I've looked at

  • Knockout JS binding initial value of dropdown list
  • Knockout does not sync manual set of option's selected attribute
  • How to pre-select an option in a dropdown knockout js

and

  • How to set initial values for Knockout's observables (for cascading lists)?

But those problems weren't quite the one I'm facing.

In my view I receive a viewmodel from an ajax call. In that object is a country ID. In a subsequent ajax call, I retrieve a list of countries (name and ID) and populate a select box from the list.

The select box is bound to the viewmodel's country ID using

<select data-bind="value: CountryId"/>

But when I populate the dropdown, the viewmodel's country is not pre-selected. I have to manually call ko.applyBindings(vm), which is a problem because the data is populated from a jQuery plugin that handles cascaded select boxes. It doesn't have references to the viewmodel (nor do I want to provide it). I could expose a callback, but that's a bit yawn.

I have created a fiddle that illustrates this problem more cleanly. If you click on the Test Select button, you will notice that the dropdown is preselected to Item 0. Uncomment the line in the js panel, and Bob's your uncle.

What am I not getting here? Isn't this a basic knockout feature?

-Jules


回答1:


So as John Earles said, adding items to the select list doesn't trigger a 'change' event. I have concluded that's actually a Good Thing. From one of the (really good) Knockout tutes:

Bindings catch DOM events and correspondingly update viewmodel properties.

That's the reverse behaviour from what I want! So I've stuck with the callback. At present it just calls applyBindings(). You can see an example in this revision of the original fiddle (callbacks etc omitted for clarity).




回答2:


You could do something like this, but you will need access to the view model:

http://jsfiddle.net/jearles/nw4cH/36/

By conditioning off the Select you prevent it from evaluating until you have populated the observableArray (in a later call).



来源:https://stackoverflow.com/questions/9832241/knockoutjs-refresh-bindings-after-populating-select-list

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