我使用knockout创建一个select元素,必须设置较晚的选项(通过从服务器加载选项来设置选项).这导致初始值丢失.下面我有一些工作代码,它做我想要的,但从服务器加载替换为静态表.
如果行setupSelect();被移动到脚本的末尾(这模拟了对服务器的异步ajax调用),然后select要求我选择.
我认为当没有选择时,值会被覆盖,然后选择到达,但值现在为空.
看起来我知道问题是什么,但不知道如何让它发挥作用.
你能告诉我如何让它发挥作用吗?
<!DOCTYPE HTML> <html> <head> <title></title> <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script> </head> <body> <p> Your thing: <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...'"> </select> <span data-bind="visible: selectedThing1"> You have chosen a thing with id <span data-bind="text: selectedThing1() ? selectedThing1() : 'unknown'"> </span>. </span> </p> <script type="text/javascript"> var viewmodel = { select: {rows: ko.observableArray() },selectedThing : ko.observable() // Nothing selected by default }; function setupSelect(){ //in the real application rows_raw is populated from a server using $.ajax var rows_raw= [ {name: "a thing",id:1},{name: "one more thing",id:2},{name: "another thing",id:3} ]; $.each(rows_raw,function(index,item){ viewmodel.select.rows.push(item); }); } //setupSelect(); //when loading from server (using $.ajax in async mode),then this line is effectivly moved to the end of the script. viewmodel.selectedThing(2); //set ititial value ko.applyBindings(viewmodel); setupSelect(); //when loading from server (using $.ajax in async mode),then this line is effectivly moved to the end of the script. </script> </body> </html>
你也可以在这里看到这两个例子http://jsfiddle.net/V33NT/1/
解决方法
这是默认的行为:Knockout强制该值与现有选项匹配,如果没有存在选项,则取消设置observable.
然而,KO 3.1中有新的设置.这被称为valueAllowUnset,它正在解决这个问题.
- 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,您可以写
<select data-bind="options: (function(){return $root.select2.rows;})(),value: selectedThing2,valueAllowUnset: true,optionsCaption: 'Choose...'">
演示JSFIddle.