click: binding doesn't work in foreach loop

2,074 views
Skip to first unread message

Luther Baker

unread,
Mar 3, 2012, 2:25:34 AM3/3/12
to KnockoutJS
I am looping over groceries ... and trying to bind "shop()" to
"click". Unfortunately, knockout can't find the 'shop' function. Am I
doing something wrong?

It works on a root level button - but doesn't work within a knockout
foreach loop.

Thanks,
-Luther


----

Uncaught Error: Unable to parse bindings.
Message: ReferenceError: shop is not defined;
Bindings value: text: name, click: shop

----

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script src="/public/javascripts/jquery-1.6.4.min.js"
type="text/javascript" charset="utf-8"></script>
<script src="/public/javascripts/knockout-2.0.0.js" type="text/
javascript" charset="utf-8"></script>
<script src="/public/javascripts/knockout.mapping-
latest.debug.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" language="javascript">

jQuery(function($){

var viewModel = {
shop : function() {
alert('go shopping');
},
groceries: [
{ name: 'apple' },
{ name: 'eggs' },
{ name: 'butter' }
]
};
ko.applyBindings(viewModel);
});
</script>
</head>
<body>


<!-- WORKS -->
<button data-bind="click: shop">Shop</button>

<!-- throws ERROR in CONSOLE -->
<ul data-bind="foreach: groceries">
<li><div data-bind="text: name, click: shop" class="link"></div></
li>
</ul>

</body>
</html>

Luther Baker

unread,
Mar 3, 2012, 2:44:48 AM3/3/12
to KnockoutJS
I believe this post answer the question ... although it doesn't
explain why.

http://groups.google.com/group/knockoutjs/browse_thread/thread/20193765eaec87b6/ae307fad84431cea?lnk=gst&q=click#ae307fad84431cea

Is it inconsistent that I must define the viewModel outside of my
jQuery ready method? And why is that only relevant within foreach
loops.

Thanks,
-Luther

gvas

unread,
Mar 3, 2012, 7:05:47 AM3/3/12
to KnockoutJS
Inside the foreach binding the context is set to the items of the
groceries array.
The shop function is a function of the viewModel object, so you should
use the following:

<ul data-bind="foreach: groceries">
<li><div data-bind="text: name, click: $parent.shop"
class="link"></div></li>
</ul>

Luther Baker

unread,
Mar 3, 2012, 10:09:10 PM3/3/12
to KnockoutJS
Thanks!

And by the way - greatly enjoying this framework. Thank you for making
it available and supporting it.

-Luther
Reply all
Reply to author
Forward
0 new messages