javascript – Knockout选择绑定,在后期添加选项时不记住值

前端之家收集整理的这篇文章主要介绍了javascript – Knockout选择绑定,在后期添加选项时不记住值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用knockout创建一个select元素,必须设置较晚的选项(通过从服务器加载选项来设置选项).这导致初始值丢失.下面我有一些工作代码,它做我想要的,但从服务器加载替换为静态表.

如果行setupSelect();被移动到脚本的末尾(这模拟了对服务器的异步ajax调用),然后select要求我选择.

我认为当没有选择时,值会被覆盖,然后选择到达,但值现在为空.

看起来我知道问题是什么,但不知道如何让它发挥作用.

你能告诉我如何让它发挥作用吗?

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title></title>
  5. <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js" ></script>
  6. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
  7. </head>
  8. <body>
  9. <p>
  10. Your thing:
  11. <select data-bind="options: (function(){return $root.select1.rows;})(),optionsText: function(item){return item.name;},optionsValue: function(item){return item.id;},value: selectedThing1,optionsCaption: 'Choose...'">
  12. </select>
  13.  
  14. <span data-bind="visible: selectedThing1">
  15. You have chosen a thing with id
  16. <span data-bind="text: selectedThing1() ?
  17. selectedThing1() :
  18. 'unknown'">
  19. </span>.
  20. </span>
  21. </p>
  22.  
  23. <script type="text/javascript">
  24. var viewmodel = {
  25. select: {rows: ko.observableArray() },selectedThing : ko.observable() // Nothing selected by default
  26. };
  27.  
  28. function setupSelect(){
  29. //in the real application rows_raw is populated from a server using $.ajax
  30. var rows_raw= [
  31. {name: "a thing",id:1},{name: "one more thing",id:2},{name: "another thing",id:3}
  32. ];
  33.  
  34. $.each(rows_raw,function(index,item){
  35. viewmodel.select.rows.push(item);
  36. });
  37. }
  38.  
  39. //setupSelect(); //when loading from server (using $.ajax in async mode),then this line is effectivly moved to the end of the script.
  40.  
  41. viewmodel.selectedThing(2); //set ititial value
  42. ko.applyBindings(viewmodel);
  43.  
  44. setupSelect(); //when loading from server (using $.ajax in async mode),then this line is effectivly moved to the end of the script.
  45. </script>
  46. </body>
  47. </html>

你也可以在这里看到这两个例子http://jsfiddle.net/V33NT/1/

解决方法

这是默认的行为:Knockout强制该值与现有选项匹配,如果没有存在选项,则取消设置observable.

然而,KO 3.1中有新的设置.这被称为valueAllowUnset,它正在解决这个问题.

Knockout.js 3.1 Released

  • With this option set to true,Knockout does not force the value to match an existing option.
  • The selection will be set to an empty option in the case of a mismatch,but the value is not overwritten.
  • This is very useful in scenarios where options are lazily loaded and there is an existing value.

因此,如果您升级到Knockout.js 3.1,您可以写

  1. <select data-bind="options: (function(){return $root.select2.rows;})(),value: selectedThing2,valueAllowUnset: true,optionsCaption: 'Choose...'">

演示JSFIddle.

猜你在找的JavaScript相关文章