Use disable binding to disable hyperlinks

2,713 views
Skip to first unread message

Douglas

unread,
Sep 13, 2011, 10:39:38 AM9/13/11
to knock...@googlegroups.com
Hello,

I'd like to disable hyperlinks using the disable binding, so that their click bindings don't fire while they are disabled.

At the moment I have an anchor like this:

<a class='today' data-bind='click: showToday, css: { disabled: isTodayShown }'>today</a>

and I just check in the showToday handler whether isTodayShown is false before running the body. But, it seems that it would be more consistent with disabling inputs if I could write this:

<a class='today' data-bind='click: showToday, disable: isTodayShown'>today</a>

and only have the click handler fire if the link is enabled. To get this functionality, it looks like I would have to change the definitions built in bindings. Is there a good way to do this without a change to core knockout?

Thanks,
Douglas




Gopal Patel

unread,
Sep 13, 2011, 12:43:27 PM9/13/11
to knock...@googlegroups.com
can link be disabled ? can you try this on button ?

Mickey

unread,
Sep 14, 2011, 2:02:21 AM9/14/11
to knock...@googlegroups.com
Hi

I am using jquery 1.6.3, jquery.tmpl 1.0.0.pre, knockoutjs 1.3.0beta.

(I tried to set an example on jsFiddle, but something is not working there)

It is working for me in IE9, but there has to be a little more to make it for WebKit (safari, chrome):
  1. there is no effect of setting "disabled" on "A" - so we need to react with something like: if (!this.enabled()) { return; } // for WebKit 
  2. IE grays out the "A" that has disabled='disabled', but for the rest I added .disabled class that is being added to disabled "A"s.

So here is my code:
<head>
<style type="text/css">
		body {
			font-familygeorgia, serif;
		}
 
		p a {
			width130px;
			displayinline-block;
		}
		
		.disabled {
		    colorGray;
		}
	</style>
<script type="text/x-jquery-tmpl" id='linkTemplate'>
<p>
		<a href="${url}" target="_blank" data-bind="text: name, enable: enabled, click: showUrl, css: { disabled: !enabled() }"></a>
		<input type="checkbox" name="toggle${id}" id="toggle${id}" data-bind="checked: enabled" />
		<label for="toggle${id}">Toggle enabled</label>
</p>
</script>

<script type="text/javascript">
var Link = function (id, name, url) {
this.id = id || new Date().getMilliseconds().toString();
this.name = name || "Name";
this.url = url || "Url";
this.enabled = ko.observable(true)
}; 
 
Link.prototype.showUrl = function () {
if (!this.enabled()) { return; } // for WebKit 
alert("url: " + this.url);
};
 
var viewModel = {
links: ko.observableArray([
new Link(1, "Google""http://www.google.com"),
new Link(2, "Microsoft""http://www.microsoft.com") 
			])
		};

$(function () {
ko.applyBindings(viewModel);
		}); 		
</script> 
</head>
<body>
	<div data-bind="template: {name: 'linkTemplate', foreach: links }"></div>
</body>

Hope it helps.
Reply all
Reply to author
Forward
0 new messages