0

I'm new to knockout and javascript. I want to create input value on input box and that value print out on document.write but kotext value is not updating on testText and changing the value on input box. I want keep print out the value to document.write and array push(textKo) process.

Source :

<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>
SomeKittens
  • 35,809
  • 19
  • 104
  • 135

1 Answers1

0

It looks like you're misunderstanding how data-binding works in Knockout. Instead of using document.write (which is a bad practice), update the view model:

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

Community
  • 1
  • 1
SomeKittens
  • 35,809
  • 19
  • 104
  • 135
  • Thank you for answer but I need each observable's final value with testText function. Do you have any idea? – user3436210 Mar 26 '14 at 21:32
  • @user3436210 check my edits, and don't forget to upvote and accept if it works. – SomeKittens Mar 26 '14 at 21:34
  • @user3436210 I think that's outside the scope of this question. Accept my answer (you'll even get rep for it!) and open a new question. – SomeKittens Mar 26 '14 at 21:57
  • @user3436210 No problem! Don't forget to click the green checkmark next to my answer – SomeKittens Mar 26 '14 at 21:59
  • I have one more question. If I need to use the 3rd party library's function on 'viewModel.kotext1();' (to like Raphael.kotext1()) this part, how can I keep use the observable? – user3436210 Mar 26 '14 at 21:59