Tags

, , ,

I’m pretty new to JavaScript, so everything said doesn’t have to be best and common way of solving problems.

Today I was working on my JavaScript project ToDoGenius (Git) and I wanted to create helper function which will be used from more than one script. So, helper script should look something like this:

var HELPERS;
if (!HELPERS) {
    HELPERS = {};
}

HELPERS.getHelloWorld = function (name) {
	return "Hello World: " + name;	
}

From html helper script can be used in following manner:

<html>
	<head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
		<script type="text/javascript" src="helpers.js"></script>          
		<script type="text/javascript">
			$(document).ready(function () {
				console.log(HELPERS.getHelloWorld("user"));
				$("#message").text(HELPERS.getHelloWorld("user"));
			});
		</script>
	</head>
	<body>
		<p>Message for you:</>
		<div id="message">
		</div>
	</body>
</html>

Code of example is on GitHub under external script.

Best 🙂

Advertisements