Knockoutjs: refresh bindings after populating sele

2019-07-20 15:21发布

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

and

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

标签: knockout.js
2条回答
干净又极端
2楼-- · 2019-07-20 15:31

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).

查看更多
混吃等死
3楼-- · 2019-07-20 15:35

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).

查看更多
登录 后发表回答