Ske*_*eve 1 javascript knockout.js
我想了解淘汰赛.有一件事我不明白.我们有html:
<p>
<input type='checkbox' data-bind="checked: hasCellphone" />
I have a cellphone</p>
<p>
Your cellphone number:
<input type='text' name='cell' data-bind="value: cellphoneNumber, enable: hasCellphone" /></p>
<button data-bind="enable: document.getElementsByName("cell")[0].value != '555'">
Do something</button>
Run Code Online (Sandbox Code Playgroud)
和JS:
function AppViewModel() {
this.hasCellphone = ko.observable(false);
this.cellphoneNumber = ko.observable("");}
ko.applyBindings(new AppViewModel());
Run Code Online (Sandbox Code Playgroud)
因此,启用输入工作,但不启用按钮,即使我在输入中输入"555"它仍然保持启用状态.
淘汰赛页面上的例子有点误导.启用绑定采用任何值,但对于自动更新,它必须是可观察的.document.getElementsByName("cell")[0].value != '555'不是一个可观察的.
您可以通过向cellphoneNumberValid模型添加一个基于cellphoneNumberobservable 值的observable来轻松修复代码:
<p>
<input type='checkbox' data-bind="checked: hasCellphone" />
I have a cellphone
</p>
<p>
Your cellphone number:
<input type='text' name='cell' data-bind="
value: cellphoneNumber,
valueUpdate: 'afterkeydown',
enable: hasCellphone" />
</p>
Run Code Online (Sandbox Code Playgroud)
做一点事
function parseAreaCode(s) {
// just a dummy implementation
return s.substr(0, 3);
}
function AppViewModel() {
this.hasCellphone = ko.observable(false);
this.cellphoneNumber = ko.observable("");
this.cellphoneNumberValid = ko.computed(function() {
return parseAreaCode(this.cellphoneNumber()) != '555';
}, this);
}
ko.applyBindings(new AppViewModel());
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/bikeshedder/eL26h/
| 归档时间: |
|
| 查看次数: |
2805 次 |
| 最近记录: |