Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot apply knockout bindings, even with the default tutorial

I am trying to apply bindings to a specific DOM element, but I am having no success with either my code or the example here

this is what I have right now:

var Test = function(first, last){
    this.first = ko.observable(first);
    this.last = ko.observable(last);
}

ko.applyBindings(new Test("Hello", "World"), $("#Element").get());

I keep getting this

Uncaught Error: ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node 

I have tried giving it only the jQuery element to no avail as well. I can confirm that $("#Element") is part of the DOM both visually and through console testing.

like image 974
jokulmorder Avatar asked Jan 17 '26 19:01

jokulmorder


2 Answers

Without any arguments $("#Element").get() does the following (doc):

Retrieve the DOM elements matched by the jQuery object.

so it returns an array of the matched elements even if this array contains only one element.

So you need to use the overload which takes an index:

ko.applyBindings(new Test("Hello", "World"), $("#Element").get(0));

Or index the returned array:

ko.applyBindings(new Test("Hello", "World"), $("#Element").get()[0]);
like image 169
nemesv Avatar answered Jan 20 '26 07:01

nemesv


jQuery's .get() function, with no parameters, returns the collection. If you want just the DOM node reference, you need to pass index 0 to it, like this:

ko.applyBindings(new Test("Hello", "World"), $("#Element").get(0));
like image 35
Richard Lindsey Avatar answered Jan 20 '26 09:01

Richard Lindsey