ChocolateChip provides method for AJAX updates and JSON data binding.

Element.xhr()
A method to perform basic HttpRequests
Element.xhrjson()
A method to perform JSON data binding.

 

Element.xhr()

The Element.xhr() method provides a way to update parts of a document with dynamic content pulled from another external document. This would normally involve document fragments, but could also be a complete document, depending on what your needs are. The If no parameters are passed, the Element.xhr() method replaces the content of the target element with the content of the requested document.

<p id="update">Old text here.</p>
$(function() {
    // This will replace the content of the paragraph above with the content of the requested document.
    $("#update").xhr("../data/newUpdate.html");
});

The Element.xhr() method can also receive and object literal of options to execute depending on the success of the HttpRequest. These are successCallback and errorCallback. The successCallback allows you to do something after the successful insertion of the new content. The errorCallback allows you to do something when HttpRequest fails. You can provide both, either one or none. Here’s an example of how to provide for both:

<p id="update">Old text here.</p>
<p id="update-message"></p>
$(function() {
    /* This will replace the content of the paragraph above with the content of the requested document. If the script is successful, it will execute the successCallback, and if it is not, it will execute the errorCallback.
*/
    $("#update").xhr("../data/newUpdate.html", {
        successCallback: function() {
            $("update-message").text("The update was successful!");
        },
        errorCallback: function() {
            $("update-message").text("There was a problem retrieving the requested file.");
        }
    });
});

Element.xhrjson()

The Element.xhrjson() method provides a way to do rudimentary data binding with JSON. You do this by passing in the URI for the JSON document you want to bind to, followed by an object literal that defines which elements of your document get mapped to which values of the JSON object. The JSON document can be created and updated dynamically on the server. That way, each time your document requests it, the bound elements in your document will be updated with the current data. It’s a good idea to have some default values in your document in case there is a problem retrieving the JSON fie.

In the example below, we are binding JSON values to the corresponding element ids in a document:

Here is a json data file named data.html:

{
	'firstName': 'Robert',
	'lastName': 'Biggs',
	'role': ' and the author of ChocolateChip', 
	'job': ' front-end developer'
}

Here is a section of HTML with some default values that we wish to replace with the values from the json file:


<div id="content"><span id='firstName'>Joe</span> <span id='lastName'>Bodoni</span> is a <span id='job'>great waiter at a restaurant downtown</span></div>

And here’s the JavaScript to get the JSON file using $.xhrjson():

$(function() {
    $("#content").xhrjson("data.html", {
            "firstName": "#firstName",
            "lastName": "#lastName",
            "role":"#role",
            "job": "#job"
	});
});

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has a $.template() method for allowing quick and simple JavaScript-based templates on the client side. This is basically a repurposing of John Resig’s (http://ejohn.org) JavaScript Micro Template framework. It’s a very small amount of code that provides the ability to create complex templates with ease.

Here’s an example of a typical template:

<script id="template_1" type="text/jsmt">
	<div>
		<% for (var i = 0; i < users.length; i++) { %>
			  <p>Name: <strong><%= users[i].fname %></strong> <em><%= users[i].lname %></em></p>
		<%  } %>
	</div>
</script>
<div id="template_1_output"></div>

First thing, notice that the JavaScript template is inserted where it the data will be output. This is not a requirement. The template can be anywhere in the document. It doesn’t matter. What matters is that the script have a unique ID so that you can get it through a DOM query and that it have a special MIME type, which is “text/jsmt.” Jsmt stands for JavaScript Micro Template, obviously there is no browser that knows what a script of type jsmt is, so browsers don’t know how to parse and display the contents of the script tag. That means none of the html will be rendered. This is not a bug in browsers, this is how they are supposed to function. If you look at the contents of the script tag you will see we have some HTML tags for defining the template’s structure and we have JavaScript enclosed in and tags. The first set, is for normal JavaScript code. The second set of tags, is used for processing a variable in the template. If you’ve used ASP or JSP in the past, you will recognize these tags.

After the $.template method processes the script tag, it outputs the result. It’s your job to decide where you want to output the result to. You can store it in a variable and out put it later, or immediately. So, from our previous example, to process the template, we use the $.template() method:

   // Process the template of ID "template_1" with JSON data in the variable "data".
    var r = $.template("template_1", data);
    // insert the results of the parsed template into the div with id "template_1_output."
    $("#template_1_output").insert(r);

We could also perform conditional checks inside the tags before outputting the data:

<script type="text/jsmt" id="jsmt_list_items">
	<% people.each(function(name) {
                // Only output names with a y in them:
		if (/y/.test(name)) { %>
		<li><%= name %></li>
	 <% }
	}); %>
</script>

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip offers two methods to enable the HTML5 dataset API for browser versions that support it. For those that do not it has a fallback using normal DOM get and set attribute methods.

Element.data()
A method add or retrieve dataset values
Element.removeData()
A method to remove a dataset from and element.

According to the dataset API in HTML5, any element can have datasets indicating information relative to that element. a dataset value always begins with “data-“. Here’s and example of an element with datasets:

<ul>
   <li data-first-name="John" data-last-name="Doe" data-occupation="teacher">John Doe<li>
   <li data-first-name="Sam" data-last-name="Smith" data-occupation="doctor>Sam Smith</li>
</ul>

Using Element.data() we can get any of the dataset values in this way:

console.log("John's occupation is: " + $("li:first-of-type").data("occupation"));

Similarly, we can set a dataset value as follows:

(function() {
   var personnelHeight = [ "5f8n", "5f10n", "6f0n" ];
   var heightnum = 0;
   $$("li").each(function(item) {
      item.data("personnel-height", personnelHeight[heightnum]);
      heightnum++;
   });
})();

To remove a dataset, use the Element.removeData() method:

(function() {
   $$("li").each(funciton(item) {
      item.removeData("first-name"); /* Removes data-first-name from each list item. */
   });
})();
Advertisements