Knockout observable不更新函数参数

时间:2014-03-26 20:54:33

标签: javascript data-binding knockout.js

我是淘汰赛和javascript的新手。我想在输入框上创建输入值,该值打印在document.write上,但kotext值不会在testText上更新并更改输入框上的值。我希望保持打印出document.writearray push(textKo)进程的值。

来源:

<head>
    <script src="knockout-3.1.0.js"></script>
</head>
<body>
<div class="sidebar">
    <div class="line">
        <label>1st Object Name</label>
        <input type="text" data-bind="value: kotext1" />
        <input type="text" data-bind="value: kotext2" />
        <input type="text" data-bind="value: kotext3" />
    </div>
</div>
<script>
var AppViewModel = function(){
    kotext1 = ko.observable("No.1!");
    kotext2 = ko.observable("No.2!");
    kotext3 = ko.observable("No.3!");
}
ko.applyBindings(AppViewModel);
testText = function(val) {
    return "This is " + val;
}
textKo = [testText(kotext1()),testText(kotext2()),testText(kotext3())];
document.write(textKo);
</script>

1 个答案:

答案 0 :(得分:0)

看起来你误解了数据绑定在Knockout中是如何工作的。不要使用document.writewhich is a bad practice),而是更新视图模型:

var viewModel =  {
    kotext1: ko.observable("No.1!"),
    kotext2: ko.observable("No.2!"),
    kotext3: ko.observable("No.3!")
}
ko.applyBindings(viewModel);
testText = function (val) {
    return "This is " + val;
}
viewModel.kotext1(testText(viewModel.kotext1()));
viewModel.kotext2(testText(viewModel.kotext2()));
viewModel.kotext3(testText(viewModel.kotext3()));

JSFiddle