Knockout Js: Indexof Always Returns -1?
Solution 1:
Besides the issue that DCoder identified — observables not taking parameters -, you had another bug here:
score = parseFloat(student.scores()[i]);
should have been
score = parseFloat(student.scores()[i]());
The nth (or i-th) element of the observable array you access there is itself an observable, so before, you where passing a function to parseFloat
, which always yields NaN.
Here is a working version: http://jsbin.com/lejezuhe/3/edit
By the way: after DCoders changes,
<td data-bind="text: $root.workMean($data, $index())"></td>
binds against a normal function, not an observable. So why does this still work?
RP Niemeyer, one of the Knockout core members writes:
In Knockout, bindings are implemented internally using dependentObservables, so you can actually use a plain function in place of a dependentObservable in your bindings. The binding will run your function inside of a dependentObservable, so any observables that have their value accessed will create a dependency (your binding will fire again when it changes).
(computed observables used to be called "dependentObservables" in earlier versions of Knockout)
For these type of issues, it really helps to be familiar with a debugger such as the one in the Chrome Developer Tools. Being able to step through your code line by line and seeing what arguments and variables actually contain is immensely helpful.
The Chrome Knockout context debugger is worthwhile to have when debugging bindings, because you can click on any DOM element and see the binding context:
Lastly, using ko.dataFor()
in the console allows you to poke around any of your existing Knockout models and viewmodels bound to the DOM:
In the Chrome console, $0
is always a reference to the DOM element you have currently selected in the Elements panel - here, a <td>
.
Post a Comment for "Knockout Js: Indexof Always Returns -1?"