rayray
rayray

Reputation: 931

KnockoutJS variables

I have the following object defined

 function BusinessUnit(id, name, code) {
             this.id = ko.observable(id);
             this.name = ko.observable(name);
             this.code = ko.observable(code);
         }

In my viewmodel I define the following

this.selectedEntry = new BusinessUnit("", "", "");

and its is bound using

$('#readID').attr('data-bind', 'text :  selectedEntry.id');

This is the error that I get

Unable to parse bindings. Message: ReferenceError: selectedEntry is not defined; Bindings value: text : selectedEntry.id

I have also tried $('#readID').attr('data-bind', 'text : $root.selectedEntry.id'); and I get the same error. Any ideas would be helpful

Upvotes: 2

Views: 1956

Answers (1)

jaffa
jaffa

Reputation: 27350

It looks like you need to prefix with the parent wrapper model around the BusinessUnit() itself. Try to reference the viewmodel variable, followed by BusinessUnit and the property around that.

Also is there any reason why you are binding using 'attr' property. Why don't you just bind in the markup? I'm not sure that ko might 'miss' binding if the attr call is after the binding. Like so:

function BusinessUnit(id, name, code) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
    this.code = ko.observable(code);
}

function ViewModel() {
    this.selectedEntry = new BusinessUnit("", "", "");
}

var vm = new ViewModel();
ko.applyBindings(vm); 

Binding markup will be:

<div id="readID" data-bind="text: vm.selectedEntry.id"></div>

I've not tested this, but hopefully you get the idea.

Upvotes: 1

Related Questions