Benjii Me
A Web Development and Programming Blog by Ben Cull
A Web Development and Programming Blog by Ben Cull
Aug 18th
Upgraded by popular demand, the jQax ajax wrapper has been turned into a full fledged jQuery plugin, conforming to the plugin authoring guidelines and compatible with compression.
Below is the full code as of writing, if you’re interested in helping out, the source can also be found here on github
Once you’ve referenced the script in the head section you can use the code like so:
var x = $.jQax({
LoaderContainerId: "#divMyLoadingDiv",
LoaderText: "I'm loading, wait up..."
});
Now you can perform the following function anywhere you need within scope of the above declaration:
var data = {
myTrackRecord: "52 Seconds",
activity: "go karts"
};
x.CallWebServiceWithJSON("MyWebService.asmx/Record", data, function (data, eventArgs) {
var result = $.parseJSON(data.d); // Please note: You may not need ".d"
// Do stuff here
});
The original non-plugin version of my code can be found in my previous post:
jQax – A Simple jQuery Ajax Wrapper with Loading Notification
Aug 14th
If you just want a simple way of connecting your web page to a .NET web service or page method using ajax, then the following snippet of javascript is for you. By the way, if you place a div with an id of “divLoader” somewhere on your page, it will automatically fade in during loading and fade out when its complete.
UPDATE: I’ve created a jQuery plugin version of this code which I’ve blogged about here!
The full code is below:
// jQax.js - A wrapper for jQuery ajax functionality aimed at .NET services and page methods
// Ben Cull - 12 August 2010
function jQax() {
this.CallWebServiceWithGET = function (WebService, GetData, ShowLoading, LoaderText, SuccessCallBack, ErrorCallback) {
if (ShowLoading)
ShowLoader(LoaderText);
if (WebService == "")
return 1; // Incorrect Parameters
if (ErrorCallback == null)
ErrorCallback = jQax.DefaultErrorCallBack;
if (typeof (GetData) === "object")
GetData = $.param(GetData);
$.ajax({
type: "GET",
url: WebService,
data: GetData,
success: SuccessCallBack,
error: ErrorCallback
});
return 0; // Successful
}
this.CallWebServiceWithJSON = function (WebService, JsonData, ShowLoading, LoaderText, SuccessCallBack, ErrorCallback) {
if (ShowLoading)
ShowLoader(LoaderText);
if (WebService == "")
return 1; // Incorrect Parameters
if (ErrorCallback == null)
ErrorCallback = jQax.DefaultErrorCallBack;
if (typeof(JsonData) === "object")
JsonData = JSON.stringify(JsonData);
$.ajax({
type: "POST",
url: WebService,
data: JsonData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: SuccessCallBack,
error: ErrorCallback
});
return 0; // Successful
};
function ShowLoader(LoaderText) {
var loadingText = "Loading...";
if (LoaderText != null && LoaderText != "") {
loadingText = LoaderText;
}
$("#divLoader").text(loadingText);
$("#divLoader").fadeIn("fast");
}
this.DefaultErrorCallBack = function (XMLHttpRequest, textStatus, errorThrown) {
var response = eval("(" + XMLHttpRequest.responseText + ")");
var output = "Message: " + response.Message + "\n\n";
output += "StackTrace: " + response.StackTrace;
alert(output);
}
$(document).ready(function () {
$("#divLoader").ajaxStop(function () {
$(this).stop(true, true).fadeOut("fast");
});
});
};
jQax = new jQax();
Well Its quite simple, if you have a page method or web service you call It like so (the call using the GET method is much the same):
jQax.CallWebServiceWithJSON(
"MyPage.aspx/MyMethod",
{
parameterName: "parameterValue",
horses: 40
}, // can be any javascript object (if json2.js is enabled), otherwise you must pass in a json string
true, // shows the divLoader
"Custom Text for Loader...", // use null for default
function(data, eventArgs) { // This is called on success
// data is exactly whats returned by the server
// quick and easy JSON parsing can be done like so:
var result = $.parseJSON(data);
// Deal with result here
});
To enable automatic JSON serialization you must download the following and add it to your head section:
json2.js from http://www.json.org/json2.js
If you want to use page methods with your fancy new ajax wrapper, you need to ensure the following two things:
Like so:
[WebMethod]
public static string MyMethod(string parameterName, string horses)
{
// Keep in mind, everything comes in and goes out as a string
return parameterName + horses;
}
Here are some links to help you out with some more complex uses of the above code:
Aug 9th
Implementing an endless scroller in Android was not actually that difficult. Here’s a quick code snippet and explanation to get you on your way.
Well here you go:
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new LoadGigsTask().execute(currentPage + 1);
loading = true;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
Ok, so all we’ve done is implement our own OnScrollListener named EndlessScrollListener, which can be called like so:
GigList.setOnScrollListener(new EndlessScrollListener());
We start our class with a few private variables which perform the following functions:
Next we have a couple of constructors that allow us to set the visibleThreshold inline if we want.
The first overridden method we have is called every time the list is scrolled. This happens many times a second during a scroll, so be wary of the code you place here. We are given a few useful parameters to help us work out if we need to load some more data, but first we check if we are waiting for the previous load to finish.
If it’s still loading, we check to see if the dataset count has changed, if so we conclude it has finished loading and update the current page number and total item count.
If it isn’t currently loading, we check to see if we have breached the visibleThreshold and need to reload more data. If we do need to reload some more data, we execute a background task and set the loading flag to true. Thus solving the problem forever!
The last method in the class we do not need, however if you’re interested, it is primarily used for tracking changes in the scroll action itself via the scrollState parameter.
Finally, the code to call the class creates a new instance of EndlessScrollListener and bind’s it to a ListView of mine. Of course put your own ListView in place of GigList.
Jul 26th
I’ve recently discovered a great new tool for MVC 2 that lets you create generic modular controls that can be shared with and used by anyone. So I built a paging control. Now you get a free Pager control AND learn how to build your own html helper. Amazing.
<% Html.RenderPager([TotalItemCount],
[PageSize],
[PageIndex],
Request.Url.Query,
[BaseUrl - It can be relative]); %>
So far with MVC 2, if you wanted to render a user control, you would use the RenderPartial method with a link to your control and possibly an accompanying model. The newly created (I’m a little slow, its actually been around since January) MvcUserControlHtmlHelpers library lets you create your own html helpers, complete with intellisense. It also lets you embed a user control absolutely anywhere in any of your views across the entire application with ease.
The beauty of this library is that we can now create simple modular user controls that anyone can quickly download and use. Let’s show you how:
<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="CoolBlogs" %>
<script runat="server">
// Declare Parameters Here
public List<string> CoolBlogs;
public int ShowItems;
</script>
<% if (CoolBlogs.Count < ShowItems)
ShowItems = CoolBlogs.Count;
%>
<div class="CoolBlogsWrapper">
<ul>
<% for (int i = 0; i < ShowItems; i++) { %>
<li><%: CoolBlogs[i] %></li>
<% } %>
</ul>
</div>
To change our MVC User Control into a html helper, we just change the Inherits attribute to MvcUserControlHtmlHelpers.UserControlHtmlHelper and give the control a name via the ClassName attribute.
<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="CoolBlogs" %>
You can add parameters to your control by adding the runat server script tags like below. You can use any public property as a parameter.
<script runat="server">
// Declare Parameters Here
public List<string> CoolBlogs;
public int ShowItems;
</script>
Next you can add some server tags to run any C# code you need, before rendering the html.
<%
if (CoolBlogs.Count < ShowItems)
ShowItems = CoolBlogs.Count;
%>
Finally, the rest is just like a regular user control, letting you add html and server tags as you like.
<div class="CoolBlogsWrapper">
<ul>
<% for (int i = 0; i < ShowItems; i++) { %>
<li><%: CoolBlogs[i] %></li>
<% } %>
</ul>
</div>
Placing the following code into the App_Code folder of you web application, compiles the code into a single assembly, allowing you to call it from anywhere inside your app.
Once placed into the App_Code folder, your new html helper can bee called by using the following code:
<% Html.RenderCoolBlogs(new List<string>() { “Benjii.Me”, “Lukencode”, “DkDevelopment” }, 3); %>
The great thing about the above code, is that it totally works with intellisense, furthering it’s usefulness as a generic control.
Jul 22nd
Own a HTC Hero? Remember how long it took HTC to update to 2.1? I certainly do, and around the fourth delay, I gave up on the idea of waiting for carriers/manufacturers to release updates. There are certainly a number of custom ROM providers out there, however I have found the most quality custom ROM team to be VillainROM.
Some Android 2.2 for HTC Hero screenshots courtesy of villainrom.co.uk
If you’re like me and love the Android platform and just want to keep up to date with its releases as they come out, to give valuable feedback and perhaps develop a couple of apps along the way then it might be an idea to flash VillainROM onto your phone.
Very soon after each Google release, VillainROM have been there to provide HTC Hero users with an opportunity to upgrade. It’s not just stock Android either, they also have HTC Sense builds as well.
Here are a few links to get you setup with a nice new OS:
Happy Upgrading!
May 11th
You can quickly and securely encrypt data in SQL Server 2005+ by using the native Symmetric Keys functionality. The most common encryption algorithms symmetric key encryption supports are Des, Triple Des, RC4 128bit, AES 128bit and AES 256bit.
To create a symmetric key, we first need to setup our database with a master key and a certificate, which act as protectors of our symmetric key store.
Create a Database Master Key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'myStrongPassword'
Create a Certificate
CREATE CERTIFICATE MyCertificateName WITH SUBJECT = 'A label for this certificate'
Now that we have setup our database, we can add the symmetric key to our certificate. To ensure we can replicate the key on another server, or rebuild the key if it is corrupted, you must very safely keep note of the KEY_SOURCE and IDENTITY_VALUE parameters, as these are what is used to create the key.
Create a Symmetric Key
CREATE SYMMETRIC KEY MySymmetricKeyName WITH IDENTITY_VALUE = 'a fairly secure name', ALGORITHM = AES_256, KEY_SOURCE = 'a very secure strong password or phrase' ENCRYPTION BY CERTIFICATE MyCertificateName;
The IDENTITY_VALUE parameter is used to generate the guid for the key and the KEY_SOURCE is used to generate the actual key. This allows you to run the above code on any server as many times as you like, with the same values, to generate the exact same key.
I’ve chosen AES_256, but you can choose from the following encryption algorithms: DES, TRIPLE_DES, RC2, RC4, RC4_128, DESX, AES_128, AES_192, and AES_256.
Finally, we can encrypt and decrypt data using the key we have just created by using the following snippets of code.
Open the Key
Before you can start encrypting or decrypting data, you must first initialize the key. This is done with the following piece of code.
OPEN SYMMETRIC KEY MySymmetricKeyName DECRYPTION BY CERTIFICATE MyCertificateName
Encrypting data
You can encrypt data by using the EncryptByKey function, like so:
DECLARE @Result varbinary(256)
SET @Result = EncryptByKey(Key_GUID('MySymmetricKeyName'), @ValueToEncrypt)
Note that the result of the above encryption is of type varbinary(256), and if you would like to store the value in a column to use this type.
Decrypting Data
You can decrypt data by using the DecryptByKey function, like so:
DECLARE @Result varchar(max) SET @Result = DecryptByKey(@ValueToDecrypt)
Make sure you decrypt to the same type that you encrypted in the first place. In my example I encrypted a varchar(max), so I also decrypted to a varchar(max).
Because symmetric keys use time based sessions, you cannot open them inside a function, however you can get around this by opening them first with a Stored Procedure, and then calling the function. Here’s an Example of the setup I have going.
The OpenKeys Stored Procedure
CREATE PROCEDURE OpenKeys
AS
BEGIN
SET NOCCOUNT ON;
BEGIN TRY
OPEN SYMMETRIC KEY MySymmetricKeyName
DECRYPTION BY CERTIFICATE MyCertificateName
END TRY
BEGIN CATCH
-- Handle non-existant key here
END CATCH
END
The Encrypt Function
CREATE FUNCTION Encrypt
(
@ValueToEncrypt varchar(max)
)
RETURNS varbinary(256)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varbinary(256)
SET @Result = EncryptByKey(Key_GUID('MySymmetricKeyName'), @ValueToEncrypt)
-- Return the result of the function
RETURN @Result
END
The Decrypt Function
CREATE FUNCTION Decrypt
(
@ValueToDecrypt varbinary(256)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(max)
SET @Result = DecryptByKey(@ValueToDecrypt)
-- Return the result of the function
RETURN @Result
END
An Example of How to Use Symmetric Keys in a Function
EXEC OpenKeys -- Encrypting SELECT Encrypt(myColumn) FROM myTable -- Decrypting SELECT Decrypt(myColumn) FROM myTable
As long as you call the OpenKeys stored procedure in the same query as the function, it will work.
May 7th
One of the cooler features of WCF web services is the ability to return your data in a range of different formats such as XML, JSON and ATOM, but what really sets it apart is just how easy it is to achieve.
Here’s a cut down, but working example from one of my project’s promote.fm. We’ll break it down below.
[WebInvoke(
Method = "GET",
UriTemplate = "search?format={format}")]
[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(List<Gig>))]
public object Search(string format)
{
// Initialize return object
List<Gig> apiGigList = new List<Gig>();
// Populate your return object here
// Decide which format to return
switch (format)
{
case "atom":
List<SyndicationItem> items = new List<SyndicationItem>();
foreach (Gig gig in apiGigList)
{
SyndicationItem item = new SyndicationItem(gig.title,
new XmlSyndicationContent("application/xml",
new SyndicationElementExtension(gig)),
new Uri(String.IsNullOrWhiteSpace(gig.externalLink)
? "http://promote.fm" : gig.externalLink),
gig.id.ToString(),
new DateTimeOffset(gig.modifiedDate == null
? (DateTime)gig.createdDate : (DateTime)gig.modifiedDate));
item.Summary = new TextSyndicationContent(gig.description);
items.Add(item);
}
SyndicationFeed feed = new SyndicationFeed("Promote.fm Gigs",
"The latest gigs promoted via promote.fm",
new Uri("http://promote.fm"),
items);
feed.Authors.Add(new SyndicationPerson("info@promote.fm",
"Promote.fm",
"http://promote.fm"));
feed.Categories.Add(new SyndicationCategory("Gigs"));
feed.LastUpdatedTime = DateTime.Now;
WebOperationContext.Current.OutgoingResponse.ContentType = ContentTypes.Atom;
return feed.GetAtom10Formatter();
case "json":
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
return apiGigList;
default:
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
return apiGigList;
}
}
Atom is more complex and requires the most code so we’ll pick that apart first.
You may have noticed that my method signature is returning an “object” instead of anything meaningful. This needs to occur to return two different types from the one method. Which types will it return then? We define these in attributes just above the constructor like so:
[ServiceKnownType(typeof(Atom10FeedFormatter))] [ServiceKnownType(typeof(List<Gig>))]
This shows that we are returning either an ATOM feed, or a List of type Gig. For now lets look at the how we built the ATOM feed.
First we need to create the list of items that make up the feed, aka a List of type SyndicationItem. This is fairly straightforward, but there are a couple of things to note.
In this example I’ve added XML data as the content for each item using the XmlSyndicationContent class, you can also use TextSyndicationContent and UrlSyndicationContent, however you can also just use a string.
Its also important to note that the summary of the SyndicationItem must be of type TextSyndicationContent but you can just pass a string to the constructor of the TextSyndicationContent class anyway.
Next we create the SyndicationFeed object. Its as simple as entering some details into the constructor, along with the list of SyndicationItem’s we created earlier. You can also add some other information to the feed such as Authors, Categories and the time it was last updated.
Now we can finally return the feed using the following two lines of code:
WebOperationContext.Current.OutgoingResponse.ContentType = ContentTypes.Atom; return feed.GetAtom10Formatter();
The first line simply lets the browser know that an ATOM feed is coming their way, and the second line delivers.
This couldn’t be easier simply set the OutgoingResponse Format depending on which type you would like to return before you actually return the object.
For JSON:
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
For XML:
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
If you are building an API using WCF, I suggest you take a quick look at my previous blog post, 5 Lifesaving Tips for Creating a WCF RESTful API in .NET 4
This should save you some time and headaches down the road.
Apr 30th
The quickest and easiest way to serialize/deserialize JSON in Android is to use Google’s GSON library. It contains almost everything you need to connect your android application to a web service that returns JSON. I’ve also included a quick filter to successfully deserialize Microsoft styled dates from JSON to Java.
Go ahead and download the latest GSON library which can be found here:
Make sure you import this into your Android project as an imported library by going to:
Project > Properties > Java Build Path > Libraries > Add Jars…
(Eclipse build id: 20100218-1602)
I would highly recommend you connect to a web service by using the java class written by my friend and I which can be found here:
Lukencode – Calling Web Services in Android using HttpClient
At the bottom of the post there is an example that returns a string of json data, just replace the [Insert JSON data here] in the below section with the code example from lukencode. For testing, however, it is a good idea to use a hard coded json, so you are not relying on timely API calls.
Lets build our deserializer by using the following code, using the type “Gig” as an example:
String jsonData = "[Insert JSON data here]";
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
Gig gig = null;
try
{
j = new JSONObject(jsonData);
gig = gson.fromJson(j.toString(), Gig.class);
}
catch(Exception e)
{
e.printStackTrace();
}
Firstly, ensure you have JSON data ready to parse. This can be gathered through a web service call, or any other method of getting JSON data. Next we setup the GSON library by using the GSON builder to create a GSON object.
After this we setup our variables and then try to parse the jsonData into a JSONObject, which is just a java object representation of the JSON data.
Once we have our JSONObject, we can try to deserialize it into a java object by using the fromJson method. To do this we pass in the JSON object we created just above, and the class that we would like to deserialize to. If a property is not found in the JSON data, it will be left as null; Also if a property inside the JSON data is not part of the targeted class, it will be ignored.
If you are like me and use WCF RESTful Web Services, you may have run into the fact that GSON cannot deserialize any Date objects. This can be fixed by making the following alterations to your code, and implementing this date deserializer I have written.
Firstly create the DateDeserializer class using the following code:
import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class DateDeserializer implements JsonDeserializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
String result = matcher.replaceAll("$2");
return new Date(new Long(result));
}
}
This class takes in a Microsoft Styled JSON Date and filters it down to an amount of milliseconds since 1 Jan 1970 GMT, allowing you to pass it into a regular Java Date object constructor. Be warned that the above code ignores the time zone of the date.
Now you can make the following alteration to the first block of code to make it look like this:
String jsonData = "[Insert JSON data here]";
GsonBuilder gsonb = new GsonBuilder();
DateDeserializer ds = new DateDeserializer();
gsonb.registerTypeAdapter(Date.class, ds);
Gson gson = gsonb.create();
JSONObject j;
Gig gig = null;
try
{
j = new JSONObject(jsonData);
gig = gson.fromJson(j.toString(), Gig.class);
}
catch(Exception e)
{
e.printStackTrace();
}
This allows us to automatically handle any date object within the JSONObject and deserialize it using our code. You should now be able to successfully deserialize json data from a web service.
I’ve been writing some Android blog posts to help android developers, especially those coming from C#, ease into android development best practices. You can find these blog posts by browsing through my Android Tag
Apr 22nd
Recently I have become obsessed with creating an android app that everyone will love. I realise that android has been out for quite some time now and I should have jumped on the bandwagon earlier, but now that I have arrived at the party, I couldn’t be happier.
I’ve owned a HTC Hero since around mid October 2009, considering I live in Australia this means I own the cutting edge of phone technology that even now, no one has even heard of, so there hasn’t been a real urge to develop for the platform. However I’ve finally taken the plunge and decided to create my very own android app. This has been met by a few hurdles I’m still climbing over.
Firstly, I’m a Microsoft stack web developer and therefore a C#, Javascript, HTML and CSS fanboy, with limited knowledge of the java language and platform. By that I mean limited to the knowledge gained by actually attending the java lectures at uni, instead of going to the uni bar
Luckily java and C# are fairly similar and the android tutorials, whilst few are available, have been quite helpful.
Secondly, the android structure of activities, layouts, views and intents (that’s all I’ve run into so far I think) is a little difficult to master straight off the bat. However I think once more people start developing and consequently start writing tutorials, it should become easier to jump on the android bandwagon as well. Also I think Google should do some more workshops in the major cities of Australia (Google, if you’re reading, I’d love to help out in Brisbane), just to spark some more excitement amongst the industry.
For anyone that may have been inspired to start developing for android, the ultimate resource can be found here:
To help anyone just starting out, the following links are the ones I’ve found the most useful to read:
Hello, World tutorial – The all important Hello World tutorial. Gets you set in no time.
Notepad tutorial – A more complicated but very useful tutorial that steps you through most of the workings of a basic android app.
Hello Views – Some great tutorials that step you through creating some of the different Views available in android.
API Demos – A list of commented code samples that show you how to implement various features of an application.
HTTP REST Client code – This was a magical find that showed me how to grab some JSON data from one of my WCF RESTful web services.
Common Tasks and How to Do Them in Android – Some helpful snippets of information for android developers.
Also be sure to check out a few Google IO videos. Even though some are a bit dated, as they were recorded in mid 2009, they still provide a wealth of information about various parts of the android system.
I’ll be sure to post some useful tutorials and tips once I’ve made some more progress with my application!
Apr 15th
Javascript classes allow you to create reusable javascript code and cleaner and leaner web sites and web applications. In this post we’ll create a javascript class and describe when and where you should use them.
Javascript classes are structured just like regular object oriented classes, they have a class signature, constructor, public properties, private variables and public and private methods. The following code is an example of how all these are laid out.
function myNotificationClass(myDefaultMessage) { //Class Declaration
// Private Variables
var defaultMessage = "Hi there";
//Public Variables
this.NotificationCount = 0;
//Constructor Start
if (myDefaultMessage != “”)
{
defaultMessage = myDefaultMessage;
}
//Private Function
function AddSignature(original) {
return original + “ – By Ben Cull”;
}
//Public Function
this.DisplayNotification = function(message) {
alert(AddSignature(message));
}
}
Now there are a few things to notice here so lets break this down and discuss each part separately.
function myNotificationClass(myDefaultMessage) {
}
A class in javascript is created the same way as a regular function, it’s what we put inside the class that really makes it useful. To access the contents of the class, we need to instantiate it like so:
var note = new myNotificationClass(“im a default message”);
Since the whole class is executed when the class is instantiated, adding some code inside the class but not inside any functions means that it will be run straight away. This mimics the purpose of a constructor and allows you to perform any setup for the class without the need for calling a function.
If you would like to pass in any parameters to the constructor, add them to the class declaration, like the above myDefaultMessage.
Private variables and methods are created the same way you would normally create them.
var defaultMessage = "Hi there";
function AddSignature(original) {
return original + “ – By Ben Cull”;
}
These variables and methods can only be accessed from within the class itself, so they are useful for helper methods and keeping track of things you don’t want your page to see.
Public variables and methods are accessible anywhere that your instance is. eg. the “note” instance we created earlier.
Its important to note that public variables and methods are created by putting “this” in front of the declarations, like so:
this.NotificationCount = 0;
this.DisplayNotification = function(message) {
alert(AddSignature(message));
}
Also note that the function keyword now comes after the function name.
To call a public function or access a public variable, you must use the instance you created above.
var myCount = note.NotificationCount; note.DisplayNotification(“Yes this is awesome”);
The quick answer is code organisation and reusability.
Start by moving your global javascript functions into their own class. This will allow you to reference the file only once, but create as many instances of it in your pages as you like. If we took the myNotificationClass for example, this would allow you to create two separate default message displays with ease, like so:
var MessageDisplayerOne = myNotificationClass("I like hotdogs");
var MessageDisplayerTwo = myNotificationClass("Icecream is my favourite");
This opens up a world of opportunity for creating complex types within javascript.
Below are two real world examples I’ve used in some of my projects to help make life easier. Check them out if you’d like a better understanding of how javascript classes are implemented.
I hope this makes it easier to manage your javascript code. Drop me an email on the Contact Me page if you have any questions.