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.
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]);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With