Skip to content

Instantly share code, notes, and snippets.

@yuxel
Created March 30, 2011 12:34
Show Gist options
  • Save yuxel/894313 to your computer and use it in GitHub Desktop.
Save yuxel/894313 to your computer and use it in GitHub Desktop.
checkboxObserver
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Checkbox Observer</title>
<script type="text/javascript" charset="utf-8" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script>
var CheckboxObserver = function (item) {
var customTriggerParam = "inner"
var itemChecked = item.is(":checked");
/**
* Toggle checkbox
*/
this.toggle = function(e) {
e = e || {};
//if its called directyl from object
if (!e.type && e.namespace != customTriggerParam) {
//TODO: 'click' should be read from event object
item.trigger("click", [customTriggerParam]);
}
//if its triggered
else if (e.type) {
itemChecked = !itemChecked;
}
};
//get checkbox status
this.isChecked = function () {
return itemChecked;
};
};
var checkboxObserver;
$(function () {
var $checkboxItem = $("#checkbox");
checkboxObserver = new CheckboxObserver($checkboxItem);
$checkboxItem.bind("click", checkboxObserver.toggle);
$("#getCurrentStatus").click(function () {
alert(checkboxObserver.isChecked());
});
$("#runFromCommandLine").click(function () {
checkboxObserver.toggle();
});
});
</script>
</head>
<body>
<input type="checkbox" id="checkbox"/>
<input type="button" id="getCurrentStatus" value="Get current checkbox status"/>
<input type="button" id="runFromCommandLine" value="Run 'checkboxObserver.toggle()' from command line"/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment