简体   繁体   中英

Knockout.JS - losing context?

In the following Fiddle I would like to be able to set the selectedFruit when clicking on one of the fruits in the list however this does not appear to be working.

After clicking on a fruit, if I inspect the value of viewModel.selectedFruit in a Chrome immediate window it appears to set the value to the viewModel object rather than the bound data item. What am I doing wrong? It appears that there is a loss of context somewhere?

JSFiddle link

Thanks

Conclusion

Whilst this helped track down the problem I was experiencing in my main app, the underlying problem was that in haste I had forgotten to use the KO template foreach binding on my <UL> and was using the templ foreach instead.

Your viewModel variable does not have global scope, as the fiddle's options are set to onLoad for how the JavaScript is loaded. If you switch it to no wrap (body) , then you will be in good shape.

The only other change is that you can just use $data directly, rather than $data() .

http://jsfiddle.net/rniemeyer/LXssJ/10/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM