How can a C # programmer write a solution in javascript?

UPDATE: It might have been unclear from my original post, but I'm mostly interested in learning about best practices for how to structure javascript code when building a solution, not just how to use the API (although this is certainly important).

I need to add functionality to a website and our team decided to address a solution using a web service that receives a call from an AJAX-formatted JSON request from the website. The web service has been created and is working fine. I have now been tasked with writing the javascript / html part of the solution.

If I were to solve this problem in C # , I would create separate classes to format the request, handle the AJAX request / response, parse the response, and finally insert the response into the DOM. I would construct properties and methods appropriately in each class, doing my best to separate functionality and structure where needed.

However, I need to solve this problem in javascript . First, how could I approach my solution in javascript the way I would apply it to C # as described above? Or more importantly, what's the best way to approach structuring your code in javascript?

Any advice or links to useful materials on the Internet is greatly appreciated.

NOTE. While this may not be directly relevant to this question, it might be worth noting that we will be using jQuery in our solution.

+2


a source to share


5 answers


I was going to recommend JQuery - it's fantastic for dealing with JSON / AJAX requests.

It looks like your main concern is encapsulation; you would like to separate your concerns. Javascript is different from C # for building OOP solutions, but you can still use many of the OOP features with Javascript. Here's a good place to get started with Javascript OOP features:

http://www.javascriptkit.com/javatutors/oopjs.shtml

At the end, you can create a class that handles all your requirements together (formatting, making an AJAX request, handling an 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();

      

Anyway, this is the main idea. There's a lot of OOP / encapsulation you can do with Javascript, depending on your style and requirements.

-Doug

+4


a source


If you're using jQuery, you already have a rich set of Ajax tools. Once you start coding, I suspect that you will find that there isn't as much complexity as you might think, given the possibilities already in the framework. Explore the jQuery API!

edit On the subject of structuring code, I again suggest advice to consider adding functionality as native jQuery plugins. It's easy to do, and it can (if done with care) make your code handy and reusable. It took me a while to recover to think about it; while used to jQuery, I tended to think in terms of utilities, to which I passed the jQuery object as a parameter:

function myCode(jq) {
  if (jq.is('div')) {
    // ...
  }
}

      

Now I find them in my old code and squirm because they really should be implemented as jQuery plugins:



jQuery.fn.myCode = function() {
  if (this.is('div')) {
    // ...
  }
  return this;
};

      

It's much cleaner to use such small plugins than the clunky functions I originally wrote.

Of course, not everything can or should be done this way; that's just some advice from my experience.

+6


a source


In fact, the fact that you are using jQuery is pretty pertinent. jQuery will give you a lot of things that you could otherwise abstract or encapsulate. For instance. just using Javascript you probably want to encapsulate the creation of the Request object based on the browser. jQuery will take care of this for you, and will also handle the response using $.ajax()

both its siblings $.get

and $.post

. Depending on what you want to do with the returned information, it is perfectly acceptable not to rebuild your javascript and do something like:

$.get('TestService.asmx/HelloWorld', function(data) {
  $('#resultElement').html(data);
});  

      

Remember the javascript has to be loaded by the client, don't weigh it if you don't need to. A lot of the OO principles you used to use with C # are really unnecessary.

+2


a source


if you are using jQuery it should be pretty simple, most of the background stuff (request formatting, response handling ... etc) is done for you.

you probably want to look into jquery.getJSON ()

in particular, the callback function will handle the returned JSON where you will parse the data ... etc.

+2


a source


This is exactly what people use jQuery for. It has Ajax and DOM manipulation, so the jQuery training site and the jQuery docs should help you hack something together.

In general, JavaScript is difficult to work with because it looks just like a typical language in the Algol family, but it misbehaves. (JavaScript doesn't have a block area, for example.) If you want to invest some time, the main book to get is Javascript: The Good Parts . The author has interesting articles on the site .

Your design is great by the way and the JS is object oriented so you could implement it. JS just inherits and encapsulates in different ways (prototypes and locks, respectively) than regular OO languages. All this is described in detail in the book cited above.

+2


a source







All Articles