11.16.2010

jQuery’s Data Method – How and Why to Use It

Description:   jQuery’s data method can make our code more concise and clean. As of jQuery 1.4.3 we also have the ability to use the method on regular JavaScript objects and listen for changes, which opens the doors to some quite interesting applications.
   

Features:  
Author: Tutorialzine
   
下載:  Download  (密碼:  見壓縮檔註解)

By dowloading you accept our Terms & Disclaimer.


Instructions:
The Basics

You can call the data method on a jQuery object, or you can use the $.data() function instead.

// Using the data method:
$("#myDiv").data("key","arbitrary value");

// Using the data function:
$.data($("#myDiv").get(0),"key","arbitrary value");

The data function is a low level implementation, and is actually being used by the method call behind the scenes. The method call is also more convenient, as it allows you to include it as a part of a chain.

Also, notice that you need to pass a DOM element as the first parameter of $.data, and not a jQuery object. This is why in this article, we are going to concentrate on using the method call instead.

When you use the data method, you need to pass two parameters – a key and a value to be stored. The key has to be a string, and the value can be any data structure, including functions, arrays and objects. There is an alternative syntax, in which you pass an object as a single parameter:

// Passing an object:
$("#myDiv").data({"name":"Stevie","age":21});

// This is the same as:
$("#myDiv").data("name","Stevie").data("age",21);

Now that you’ve inserted your data, you can read it by calling the data method with a single parameter – the key:
var theValue = $("#myDiv").data("age"); // 21

You can access the data everywhere in your script. It doesn’t matter what the selector is, as long as it is the same element, you will get the same value you’ve put in:

// Given that myDiv is the first div in the page:

var theValue = $("div:first").data("name"); // Stevie

$("div:first").click(function(){
	alert($(this).data("age"); // 21
});

As of jQuery 1.4.3 HTML5 data- attributes are also made available via the data method. This means that if you have an element like this:
<img id="img1" data-internal-id="221" width="100" height="100" />

You can access the data-internal-id attribute by just calling $("#img1").data('internal-id'), which is really useful in AJAX applications. We also used this technique in last week’s tutorial

Using the Data Method on JavaScript objects

You may find it surprising that you can use the data method on regular JavaScript objects. This functionality has been around for some time, but with jQuery 1.4.3 it opens the doors to some useful applications.

var myObj = {};
$(myObj).data("city","Springfield");

What the snippet above does, is actually create a city property on the object. But why not just set myObj.city = "Springfield" yourself? Because the data method triggers a number of useful events you can listen for:

var progressBar = {};

$(progressBar).bind('setData',function(e,key,value){
    switch(key){
        case "percent":
            $("#progress").width(value+"%");
            $("#percentText").text(value+"%");
            break;

        case "color":
            $("#progress").css("color",value);
            break;

        case "enabled":
            $('#progress').toggleClass("active",value);
            break;
    }
});

$(progressBar).data("enabled",true).data("percent",21).data("color","green");

// You also have easy access to the current values:
console.log(progressBar.enabled);    // true

In the fragment above, we use the data method to create a simple API with which we can update a progress bar on screen. The best part of it is that at any given time you can just take a peek at the progressBar object and get the current values.

    If you believe that your work has been copied in a way that constitutes copyright infringement, or that your intellectual property rights have been otherwise violated, please e-mail us

0 留言:

發佈留言

您使用留言則表示同意及遵守使用條款及守則

建議: 為方便留言回覆,請不要用匿名方式 留言。