简体   繁体   中英

knockout simple binding not working

I am trying a simple example for binding an objects' attribute to a UI.

My example is here http://jsfiddle.net/arendu/m14mohda/17/

I have the following HTML:

The name is <span data-bind="text: personName"></span>
<button type="button" onlick="changeName()">Click Me!</button>

And the following js script:

var myViewModel = {
    personName: ko.observable('Foo'),
    personAge: ko.observable(123)
};

var changeName = function () {
    myViewModel.personName("Bar")
}
ko.applyBindings(myViewModel);

My question is why does the displayed name not change from 'Foo' to 'Bar' when the button is clicked?

Thanks

This myViewModel.personName = 'Bar' is not going to work, since personName is an observable. When we want to get the observable's value, we simple call it as a function

 myViewModel.personName()

While, when we want to set it's value, we call it like above but passing the value as a parameter.

 myViewModel.personName("Bar")

You can think it as a getter and a setter.

 var myViewModel = { personName: ko.observable('Foo'), personAge: ko.observable(123) }; myViewModel.changeName = function () { myViewModel.personName('Bar'); } ko.applyBindings(myViewModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> The name is <span data-bind="text: personName"></span> <button type="button" data-bind="click: changeName">Click Me!</button> 

There were a few problems with your code. The primary issue was in the way you were trying to set an observable. Observables should be used as getter/setter functions.

http://jsfiddle.net/m14mohda/16/

The name is <span data-bind="text: personName"></span>
<button type="button" data-bind="click: changeName">Click Me!</button>

var myViewModel = {
    personName: ko.observable('Foo'),
    personAge: ko.observable(123)
};

myViewModel.changeName = function() {
    var newName = myViewModel.personName() === 'Foo' ? 'Bar' : 'Foo';
    myViewModel.personName(newName);
}
ko.applyBindings(myViewModel);

First: You never use inline event handlers with knockout. Period. Everything is done through bindings.

Second: You should use classes as viewmodels, it will make your life easier.

 function Person(name, age) { this.name = ko.observable(name), this.age = ko.observable(age) } Person.prototype.changeName = function () { this.name('Bar'); }; ko.applyBindings( new Person('Foo', 123) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> The name is <span data-bind="text: name"></span> <button data-bind="click: changeName">Click Me!</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM