UPDATE: Perhaps this wasn't clear from my original post, but I'm mainly interested in knowing a best practice for how to structure javascript code while building a solution, not simply learning how to use APIs (though that is certainly important).
I need to add functionality to a web site and our team has decided to approach the solution using a web service that receives a call from a JSON-formatted AJAX request from within the web site. The web service has been created and works great. Now I have been tasked with writing the javascript/html side of the solution.
If I were solving this problem in C#, I would create separate classes for formatting the request, handling the AJAX request/response, parsing the response, and finally inserting the response somehow into the DOM. I would build properties and methods appropriately into each class, doing my best to separate functionality and structure where appropriate.
However, I have to solve this problem in javascript. Firstly, how could I approach my solution in javascript in the way I would approach it from C# as described above? Or more importantly, what's a better way to approach structuring code in javascript?
Any advice or links to helpful material on the web would be greatly appreciated.
NOTE: Though perhaps not immediately relevant to this question, it may be worth noting that we will be using jQuery in our solution.
UPDATE: Perhaps this wasn't clear from my original post, but I'm mainly interested in knowing a best practice for how to structure javascript code while building a solution, not simply learning how to use APIs (though that is certainly important).
I need to add functionality to a web site and our team has decided to approach the solution using a web service that receives a call from a JSON-formatted AJAX request from within the web site. The web service has been created and works great. Now I have been tasked with writing the javascript/html side of the solution.
If I were solving this problem in C#, I would create separate classes for formatting the request, handling the AJAX request/response, parsing the response, and finally inserting the response somehow into the DOM. I would build properties and methods appropriately into each class, doing my best to separate functionality and structure where appropriate.
However, I have to solve this problem in javascript. Firstly, how could I approach my solution in javascript in the way I would approach it from C# as described above? Or more importantly, what's a better way to approach structuring code in javascript?
Any advice or links to helpful material on the web would be greatly appreciated.
NOTE: Though perhaps not immediately relevant to this question, it may be worth noting that we will be using jQuery in our solution.
Share Improve this question edited May 11, 2014 at 18:53 nicael 19.1k13 gold badges62 silver badges92 bronze badges asked May 12, 2010 at 14:42 Ben McCormackBen McCormack 33.2k49 gold badges154 silver badges225 bronze badges 3- 2 I think, as is the case with every programming environment, that you should plan on implementing a Javascript solution the way a Javascript programmer would do it. Trying to make Javascript look/act like something it's not is an oft-repeated mistake. – Pointy Commented May 12, 2010 at 14:48
- @Pointy I see what you're saying and I pletely agree. Through this question, I'm hoping to get feedback from others who may have walked the same path from C# to javascript and can offer good advice. – Ben McCormack Commented May 12, 2010 at 14:49
- OK cool - well I'll leave my ment there as advice to the youth of tomorrow :-) – Pointy Commented May 12, 2010 at 14:50
5 Answers
Reset to default 6If you're using jQuery, you've already got a rich set of Ajax tools. Once you start writing the code I suspect you'll find that there's not as much plexity as you think, given the capabilities already in the framework. Study the jQuery APIs!
edit As to structuring code, well, again I'd offer the advice to consider adding functionality in the form of jQuery plugins of your own. It's easy to do, and it can (if done with care) make your code maintainable and reusable. It took me a while to e around to thinking about things that way; while getting used to jQuery, I had a tendency to think in terms of utilities to which I'd pass a jQuery object as a parameter:
function myCode(jq) {
if (jq.is('div')) {
// ...
}
}
Now I find those in my old code and squirm, because they really should be done as jQuery plugins:
jQuery.fn.myCode = function() {
if (this.is('div')) {
// ...
}
return this;
};
Much cleaner to use such little plugins than clumsier functions as I originally wrote them.
Of course not everything can or should be done that way; that's just some advice from my experience.
I was about to remend JQuery - it's fantastic for working with JSON/AJAX requests.
It sounds like your primary concern is encapsulation; you'd like to separate your concerns. Javascript has a different feel from C# for creating OOP solutions, but you can still take advantage of many OOP features with Javascript. Here's a good place to get started with Javascript's OOP features:
http://www.javascriptkit./javatutors/oopjs.shtml
In the end, you can create a class that handles each of your requirements together (formatting, performing AJAX query, handling AJAX response):
$.DataHandler = new function()
{
this.MyData = "Default Value",
this.FormatData = function() { return this.MyData; }
this.HandleResponse = function(data) { ... do something ... }
this.DoAJAX = function()
{
$.ajax({
type: "GET",
url: "/path/to/your/ajax",
data: this.FormatData(),
dataType: "json",
success: this.HandleResponse
});
}
}
I haven't tested the above code, but you get the idea. Later, you can do something like this:
$.DataHandler.MyData = "Some other data";
$.DataHandler.DoAJAX();
Anyhow, that's the basic idea. There's a lot of OOP/encapsulation you can do with Javascript, depending on your style and requirements.
-Doug
Actually the fact that you are using jQuery is pretty relevant. jQuery will give you a lot of the things you would otherwise abstract away or encapsulate. E.g. just using Javascript, you would probably want to encapsulate the creation of a Request object based on browser. jQuery takes care of this for you, as well as handling the response by using $.ajax()
and its relatives $.get
and $.post
. Depending on what you want to do with the returned information, it is perfectly acceptable to not over architect your javascript and do something like:
$.get('TestService.asmx/HelloWorld', function(data) {
$('#resultElement').html(data);
});
Remember that javascript has to be loaded by the client, don't weigh it down unless you have to. A lot of the OO principles you're used to using with C# aren't really necessary.
if you are using jQuery it should be pretty simple, most of the background stuff (formatting the request, handling the response...etc) is done for you.
you probably want to look into jquery.getJSON()
specifically the callback function is going to be where you would handle the returned JSON -where you would parse the data...etc
This is just the sort of thing people use jQuery for. It has Ajax and DOM manipulation covered, so the learning jQuery site and the jQuery docs should help you hack something together.
In general, JavaScript is tough to work with because it looks just like a typical Algol-family language, but misbehaves in subtle ways. (For instance, JavaScript does not have block scope.) If you want to invest some time, the basic book to get is Javascript: The Good Parts. The author has some interesting articles at his website.
Your design, btw, is perfectly fine, and JS is object-oriented, so you could certainly implement it. JS just does inheritance and encapsulation differently (prototypes and closures, respectively) than mainstream OO languages. This is all covered in adequate detail in the book cited above.