简体   繁体   中英

Knockout binding not updating

My knockout binding is not updating. I have a field that I have set as

this.firstName = ko.observable("Bert");

When I call:

AppViewModel.firstName(name);

I need it to update. Here is a jsfiddle:

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());

// When I click button I want the name to change
$('input[type=button]').click( function() {
    var name = 'New Name';
    AppViewModel.firstName(name);
});    

http://jsfiddle.net/d577K/38/

When you write

new AppViewModel()

you're creating a new AppViewModel object. However you never save a reference to that object.

when you try to update AppViewModel.firstName(name); , AppViewModel is your constructor function and you're calling a method that doesn't exist on the constructor function. You need to create your object as a variable and then reference it.

var app = new AppViewModel();

...

app.firstName(name);

Here's an update to your fiddle , its working now.

You're referencing the AppViewModel class instead of the actual object... try instantiating the view model before binding with knockout, then reference the instance:

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}
var vm = new AppViewModel();
// Activates knockout.js
ko.applyBindings(vm);

//When I click button I want the name to change
$('input[type=button]').click( function() {
var name = 'New Name';
vm.firstName(name);

});

Here's the fiddle: http://jsfiddle.net/d577K/178/

Any reason to keep the name update function outside of the model?

How about this: http://jsfiddle.net/dvdrom000/d577K/41/

html update

<input type="button" value="test" data-bind="click: NewName" />

js

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");

    this.NewName = function(){
        this.lastName("New name");
    }
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());

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