Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for JavaScript

June 18, 2014

JavaScript Function Terminology

Filed under: JavaScript @ 12:43 pm

I have been working on and off with JavaScript since 2001. But its one thing to use JavaScript functions and another thing entirely to know the vocabulary of JavaScript functions.

So here are some common JavaScript function terms:

Function Declaration

Defines a named function.

function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Calling:

  • onClick() – executes the function and returns the value.
  • onClick – references the function.

In JavaScript, function declarations are always moved (“hoisted“) to the top of their scope at runtime. This means that the function does not need to be declared before it is used.

So something like this is valid:

onClick(“OK”);

function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Function Expression

Defines a function as part of a larger expression such as a variable assignment.

The function can be named, as with the onClick function below:

var buttonClick = function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Or anonymous as with this function:

var buttonClick = function(buttonName) {

    return “Clicked: ” + buttonName;

}

Calling:

  • buttonClick() – executes the function and returns the value.
  • buttonClick – references the function.
  • onClick() – generates an undefined error.

Function expressions are not “hoisted”. So attempting to use them before they are defined generates a type error:

buttonClick(“OK”);

var buttonClick = function(buttonName) {

    return “Clicked: ” + buttonName;

}

NOTE: The variable declaration (buttonClick) does get hoisted, but only the definition, not the assignment. So at runtime, var buttonClick = undefined is hoisted. But the assignment does not occur until the un-hoisted assignment statement is executed.

Function Statement

Basically a function declaration. (See above).

Guidance

In general, guidance says to favor function expressions over function declarations (or function statements) for the following reasons:

  • The hoisting of function declarations can cause confusion or hard to find bugs.
  • Function expressions more clearly imply that the function itself is an object.

See this link for more examples and an enhanced discussion of function declarations vs function expressions.

Enjoy!

September 24, 2012

Building a JavaScript Client for a Web API Service

Filed under: ASP.NET,ASP.NET Web API,C#,JavaScript,VB.NET @ 12:54 am
An ASP.NET Web API service provides support for many different types of client applications. One such client is a JavaScript application. This post provides a very simple JavaScript client you can use to test your Web API service.

[See this prior post for an introduction to building an ASP.NET Web API service. The service created in that post is the example service used here.]

Here is the HTML/JavaScript code to display all of the key/value pairs for a single object returned by a Web API service.

<!DOCTYPE html> <html lang=”en”> <head> <title>Customer Information</title> <script src=”../../Scripts/jquery-1.7.1.min.js” type=”text/javascript”></script> <script type=”text/javascript”> $(document).ready(function () { // Send an AJAX request for Customer Info $.getJSON(“api/customer/2″, function (data) { // On success, ‘data’ contains the customer details. $.each(data, function (key, val) { // Format the text to display. var str = key + ‘: ‘ + val;

                    // Add a paragraph for each property. $(‘#info’).append(‘<p>’ + str + ‘</p>’); }) })

             // Handle a fail .fail( function (jqXHR, textStatus, err) { $(‘#info’).html(‘Error: ‘ + err); }); }); </script> </head>

<body> <div> <h1>Customer Account Information</h1> <p id=’info’ /> </div> </body>

</html>

If you followed the prior post mentioned above and built the sample Web API service, you can delete all of the code from the Index.cshtml file and replace it with the above code.

When you run the application, you get this:

image

Let’s go through the JQuery script code. The example uses the 1.7.1 version of JQuery. The script itself does the following:
  • $.getJSON: Gets the JSON format of the data returned when passing “api/customer/2″ to the Web API service. You can change the url string passed to the service to match any url accepted by your service.
  • $.each: Iterates over each object, executing a function for each one. In this case, it processes each name/value pair provided by the JSON format.
    • It builds a string with the name of the field, a colon, and the value.
    • It adds the string to a paragraph element and then appends the paragraph to an element with an Id of #info.
  • .fail: Provides error information if an error is returned by the service.

The HTML code displays the header and a paragraph placeholder that is extended by the script.

If you want to display a set of business objects with their name/value pairs, you can change the script as follows:

<script type=”text/javascript”> $(document).ready(function () { // Send an AJAX request for Customer Info $.getJSON(“api/customer”, function (data) { // On success, ‘data’ contains the customers details. $.each(data, function (key, row) {

                $(‘#info’).append(‘<p>’ + ‘Item: ‘ + key + ‘</p>’); // Process each customer (“row”) $.each(row, function (rowKey, rowValue) {

                    // Format the text to display. var str = rowKey + ‘: ‘ + rowValue;

                    // Add a paragraph for each property. $(‘#info’).append(‘<p style=”text-indent: 5em;”>’ + str + ‘</p>’); }) }) })

         // Handle a fail .fail( function (jqXHR, textStatus, err) { $(‘#info’).html(‘Error: ‘ + err); }); }); </script>

This script includes two .each methods, the first one processes each customer and the second one processes each field of the customer from the JSON.

The result of this script is shown below:

image

Notice that both scripts could be used for any set of JSON objects returned from a Web API service. You just need to change the url string as appropriate for the service.

Enjoy!

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs