Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent anchor navigation with click binding using knockout

Tags:

knockout.js

I'm trying to find a way to have an attr (href) binding and a click binding on the same anchor tag, and have the function bound to the click to decide whether navigation is allowed.

In plain html this would be something like Something In that case if the the function decideNavigation returned true, the navigation to '/' would occur and if it was false, the navigation would be prevented.

At the moment, if I bind a click function, the navigation is just totally blocked.

Any simple way to do this with knockout or would it require something like a custom binding?

Thanks.

like image 570
Adam Avatar asked Dec 25 '22 20:12

Adam


2 Answers

Looking at the knockoutjs documentation for the click binding, under note #3 it explains that by default the navigation to the href is canceled, but you can override it by returning true from your function.

like image 82
Nathan Fisher Avatar answered Feb 19 '23 07:02

Nathan Fisher


Is the click binding to a function? If so, have the function perform it's logic and then return true/false. If it returns false, it should kill the navigation to the page specified in the href. If it returns true, navigation should proceed.

'a href="mypage.html" onclick="return myfunction'

function myFunction() { return (my condition == true) ? true : false; }

like image 42
Gary Richter Avatar answered Feb 19 '23 06:02

Gary Richter