Knockout.js:填充选择列表后刷新绑定 [英] Knockoutjs: refresh bindings after populating select list

查看:101
本文介绍了Knockout.js:填充选择列表后刷新绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得必须先问这个问题,但是我已经看过了

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

但是这些问题并不是我所面临的.

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

在我看来,我从ajax调用中收到一个viewmodel.在该对象中是一个国家/地区ID.在随后的ajax调用中,我检索了一个国家(名称和ID)列表,并从列表中填充了一个选择框.

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.

选择框使用以下方式绑定到视图模型的国家/地区ID:

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

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

但是当我填充下拉列表时,未预先选择视图模型的国家/地区.我必须手动调用ko.applyBindings(vm),这是一个问题,因为数据是从处理级联选择框的jQuery插件中填充的.它没有对viewmodel的引用(我也不想提供它).我可以公开一个回调,但这有点打哈欠.

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.

我创建了小提琴,它更清楚地说明了这个问题.如果单击测试选择"按钮,您会注意到该下拉列表已预先选择为项目0.在js面板中取消注释该行,而Bob是您的叔叔.

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?

-朱尔斯

推荐答案

因此,正如约翰·厄尔斯(John Earles)所说,将项目添加到选择列表不会触发更改"事件.我已经得出结论,这实际上是一件好事.从(非常好的)淘汰赛之一中:

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:

绑定捕获DOM事件并相应地更新viewmodel属性.

Bindings catch DOM events and correspondingly update viewmodel properties.

那是我想要的相反行为!所以我坚持使用回调.目前,它仅调用applyBindings().您可以在原始小提琴的此版本中看到一个示例(为清楚起见,省略了回调等).

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

这篇关于Knockout.js:填充选择列表后刷新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆