Simple link doesn't work

58 views
Skip to first unread message

I Grog

unread,
May 24, 2012, 8:50:29 AM5/24/12
to KnockoutJS
In this code: http://jsfiddle.net/PDwBF/1/
link to google doesn't work. How to repair it?

<ul data-bind="foreach: Items">
<li data-bind="click: $root.SetCurrent">
<p data-bind="text: id"></p>
<div>
<a href="http://google.com" target="_blank">Go to google</
a>
</div>
</li>
</ul>

function ViewModel()
{
var self = this;
self.SelectedItem = ko.observable();
self.Items = ko.observableArray([]);
self.SetCurrent = function(item)
{
self.SelectedItem(item);
};
};

var vm = new ViewModel();
ko.applyBindings(vm);

vm.Items.push({id: 55});
vm.Items.push({id: 66});
vm.Items.push({id: 77});

rpn

unread,
May 24, 2012, 8:57:13 AM5/24/12
to knock...@googlegroups.com
Hello-
One option is to return true; from your SetCurrent methood, which will allow the default action to proceed like: http://jsfiddle.net/rniemeyer/PDwBF/3/ 

I Grog

unread,
May 31, 2012, 3:28:43 AM5/31/12
to KnockoutJS
Thanks, but what is wrong with button tag and click binding?

Why it doesn't work as expected?

http://jsfiddle.net/6jXW7/1/


<ul data-bind="foreach: Items">
<li data-bind="click: $root.SetCurrent">
<p data-bind="text: id"></p>
<div>
<a href="http://google.com" target="_blank">Go to google</
a>
<button data-bind="click: $root.DoIt($data)">Do It</
button>
</div>
</li>
</ul>

function ViewModel()
{
var self = this;
self.SelectedItem = ko.observable();
self.Items = ko.observableArray([]);
self.SetCurrent = function(item)
{
self.SelectedItem(item);
return true;
};
self.DoIt = function(item)
{
console.log(item.id);

Philip Steinebrunner

unread,
May 31, 2012, 4:21:03 AM5/31/12
to KnockoutJS
Hi

It's because you write "$root.DoIt($data)" but you should write
"$root.DoIt". With your writing the function gets executed when ko
setting up the bindings and returns void to the click binding handler.
You don't have to pass $data to the function because thats implicitly
done by knockout already.

Here is the correct code:
http://jsfiddle.net/philipooo/6jXW7/2/

- Philip

I Grog

unread,
May 31, 2012, 5:03:40 AM5/31/12
to KnockoutJS
Thanks,
I've added in SetCurrent console.log command

http://jsfiddle.net/6jXW7/3/

Why if I press button, SetCurrent function also executes?
I don't need it, how to avoid it?

philip.ste...@googlemail.com

unread,
May 31, 2012, 5:12:18 AM5/31/12
to knock...@googlegroups.com
Because you handle all clicks within the list-item. You can prevent this by adding clickBubble: false to the button-binding:
<button data-bind="click: $root.DoIt, clickBubble: false">Do It</button>

I Grog

unread,
May 31, 2012, 5:15:12 AM5/31/12
to KnockoutJS
Thanks
Reply all
Reply to author
Forward
0 new messages