ipengineer
ipengineer

Reputation: 3307

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/

Upvotes: 1

Views: 8235

Answers (3)

Glen Hughes
Glen Hughes

Reputation: 4812

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/

Upvotes: 2

roman m
roman m

Reputation: 26531

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());

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25728

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.

Upvotes: 2

Related Questions