Вопрос

I created a Plunker here: http://plnkr.co/edit/EWh3DI8fkckU9mKGqWhS

I am either very tired or just not able to see what's going on. This code displays "Hello World" in the text box in VS 2013 but for some reason jQuery doesn't seem to be working in Plunker. I'm new to Plunker and that's not really my question.

My question is how to get the Clear Text Box button to clear the text in the text box using a Knockout observable. I created a simple model using the Revealing Pattern and then defined the value in the text box to be an observable (using data-bind and applybindings). But setting the vm public variable after KO binding doesn't change the value in the text box.

What am I missing?

Это было полезно?

Решение

Your apply bindings function needs an ending parenthesis

$(function () {  
    ko.applyBindings(vm);
  }) <--here

essayText should be and observable

var essayText = ko.observable("Hello World");

and thus, essayText should be modified the way observables are modified

function cleartb()
  {
    vm.essayText('');
    return;
  }

Другие советы

I like plunker, but for these quick help questions, JSFiddle with cdnjs for external resources are faster (IMO). Anyway, here's a different approach and here's a JSFiddle

var ViewModel = function(){
    var _self = this;
    _self.EssayText = ko.observable("Hello World");
    _self.ClearTextBox = function(){
      _self.EssayText("");  
    };
};

ko.applyBindings(new ViewModel());

The Markup

<div class="container">
    <div class="row">
        <div class="col-md-2">Enter Text Here (Starting Value Should Be 'Hello World'):</div>
        <div class="col-md-10">
            <textarea id="TextEditor" data-bind="value: EssayText"></textarea>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <button class="btn btn-info" data-bind="click: ClearTextBox">Clear Text Box</button>
        </div>
    </div>
</div>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top