Search code examples
c#javascriptencapsulation

How might a C# programmer approach writing a solution in javascript?


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.


Solution

  • 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