views:

181

answers:

5

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.

+6  A: 

If 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 complexity 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 come 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.

Pointy
I'm getting tired of fighting the belief that jQuery is the magic solution to _all_ problems..
Sean Kinsey
@Sean - that's why you just embrace the fact. :)
Doug
Well, @Sean, it isn't a magic solution of course, but when the question clearly stipulates that jQuery is to be used, and the problem at hand is something that jQuery supports well, there's nothing inappropriate about encouraging study of the API.
Pointy
@Pointy, I actually missed that one :)
Sean Kinsey
@Pointy Thanks for adding the comments on structuring code. That helps. I'll be using jQuery in my solution, but do I have to pass in the jQuery object or can I simply put a `$` in my custom function and consume jQuery there? If I don't need to pass in jQuery, do I really need to create a plug-in?
Ben McCormack
If you're writing code that really doesn't have much to do with the DOM, then there's not much cause to make it have anything to do with jQuery. You might want to think about *organizing* it a little like jQuery, with your own single global "focal point" object under which you collect your own code.
Pointy
+2  A: 

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.

Nick
+2  A: 

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

David Larrabee
@David Thanks for the suggestion. I should note, however, that I can't use `jquery.getJSON()` because it uses a `http get` request, which I cannot use because an ASP.NET AJAX-enabled web service requires `http post` for security reasons. However, you can still use `jquery.ajax` just fine.
Ben McCormack
good to know, I haven't actually used it in practice on a .NET site myself - but will have to keep that in mind if I end up needing to do so. thanks!
David Larrabee
+4  A: 

I was about to recommend 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.com/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

Doug
@Doug encapsulation is exactly what I'm looking to do. Thanks for the link!
Ben McCormack
No problem, hope it helps :)
Doug
+2  A: 

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.

jared