github github
  • Home
  • Pricing and Signup
  • Training
  • Gist
  • Blog
  • Login

jquery / jquery-datalink

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
    • 233
    • 11
  • Source
  • Commits
  • Network
  • Pull Requests (2)
  • Issues (11)
  • Graphs
  • Branch: master

click here to add a description

click here to add a homepage

  • Switch Branches (1)
    • master ✓
  • Switch Tags (0)
  • Branch List
Sending Request…
Downloads

A data linking plugin for jQuery. — Read more

  Cancel

  Cancel
  • HTTP
  • Git Read-Only

This URL has Read+Write access

Update the copyright header to point to the Software Freedom Conservancy. 
jeresig (author)
Tue Oct 19 18:36:29 -0700 2010
commit  aa81d4438b21b068c72b
tree    5d2b4650681aece59675
parent  8e53293f66d6d4a50202
jquery-datalink /
name age
history
message
file README.md Mon Oct 04 06:55:25 -0700 2010 Updated readme to point to the new documentatio... [BorisMoore]
directory demos/ Mon Oct 11 18:07:38 -0700 2010 Removed the out-of-date version of jquery.tmpl. [BorisMoore]
file jquery.datalink.js Tue Oct 19 18:36:29 -0700 2010 Update the copyright header to point to the Sof... [jeresig]
file jquery.js Fri Oct 01 16:13:15 -0700 2010 Updated jQuery build, readme, and header. [InfinitiesLoop]
file jquery.min.js Fri Oct 01 16:13:15 -0700 2010 Updated jQuery build, readme, and header. [InfinitiesLoop]
README.md

jQuery Data Link plugin

Documentation for the jQuery Data Link plugin can be found on the jQuery documentation site: http://api.jquery.com/category/plugins/data-link

==================================== WARNING ====================================
Note: This plugin currently depends on jQuery version 1.4.3 which is not released yet. You can use a recent build from the jQuery repository, included in this repository for convenience as 'jquery.js' and 'jquery.min.js'.
=================================================================================

Introduction

This proposal describes how support for "data linking" can be added to the jQuery core library. The term "data linking" is used here to mean "automatically linking the field of an object to another field of another object." That is to say, the two objects are "linked" to each other, where changing the value of one object (the 'source') automatically updates the value in the other object (the 'target').

jQuery(..).link() API

The link API allows you to very quickly and easily link fields of a form to an object. Any changes to the form fields are automatically pushed onto the object, saving you from writing retrieval code. By default, changes to the object are also automatically pushed back onto the corresponding form field, saving you from writing even more code. Furthermore, converters lets you modify the format or type of the value as it flows between the two sides (for example, formatting a phone number, or parsing a string to a number).

var person = {};
$("form").link(person);
$("#name").val("foo");
alert(person.name); // foo
// ... user changes value ...
alert(person.name); // <user typed value>
$(person).data("name", "bar");
alert($("#name").val()); // bar

The jQuery selector serves as a container for the link. Any change events received by that container are processed. So linking with $("form") for example would hookup all input elements. You may also target a specific element, such as with $("#name").link(..).

Customizing the Mapping

It is not always that case that the field of an object and the name of a form input are the same. You might want the "first-name" input to set the obj.firstName field, for example. Or you may only want specific fields mapped rather than all inputs.

var person = {};
$("form").link(person, {
    firstName: "first-name",
    lastName: "last-name",
});

This links only the input with name "first-name" to obj.firstName, and the input with name "last-name" to obj.lastName.

Converters and jQuery.convertFn

Often times, it is necessary to modify the value as it flows from one side of a link to the other. For example, to convert null to "None", to format or parse a date, or parse a string to a number. The link APIs support specifying a converter function, either as a name of a function defined on jQuery.convertFn, or as a function itself.

The plugin comes with one converter named "!" which negates the value.

var person = {};
$.convertFn.round = function(value) {
    return Math.round( Math.parseFloat( value ) );
}
$("#age").link(person, {
    age: {
        convert: "round"
    }
});
$("#name").val("7.5");
alert(person.age); // 8

It is nice to reuse converters by naming them this way. But you may also specified the converter directly as a function.

var person = {};
$("#age").link(person, {
    age: {
        convert: function(value) {
            return Math.round( Math.parseFloat( value ) );
        }
    }
});
$("#name").val("7.5");
alert(person.age); // 8

Converter functions receive the value that came from the source, the source object, and the target object. If a converter does not return a value or it returns undefined, the update does not occur. This allows you to not only be able to convert the value as it is updated, but to customize how the value is assigned.

var person = {};
$("#age").link(person, {
    age: {
        convert: function(value, source, target) {
            var age = Math.round( Math.parseFloat( value ) );
            target.age = age;
            target.canVote = age >= 18;
        }
    }
});
$("#name").val("7.5");
alert(person.age); // 8
alert(person.canVote); // false
$("#name").val("18");
alert(person.canVote); // true

In this example, the converter sets two fields on the target, and neglects to return a value to cancel the default operation of setting the age field.

Converters can also be specified for the reverse process of updating the source from a change to the target. You can use this to customize the attribute used to represent the value, rather than the default of setting the 'value'.

var product = { };
$("#rank").link(product, {
    salesRank: {
        convertBack: function(value, source, target) {
            $(target).height(value * 2);
        }
    }
});
$(product).data("salesRank", 12);
alert($("#rank").height()); // 24

This example links the height of the element with id "rank" to the salesRank field of the product object. When the salesRank changes, so does the height of the element. Note in this case there is no linking in the opposite direction. Changing the height of the rank element will not update the product.salesRank field.

Updating immediately

Sometimes it is desired that the target of a link reflect the source value immediately, even before the source is changed. Currently there is no built-in API for this, but you can force by triggering a change event.

$(source)
    .link(target)
    .find("#input1").trigger("change");
alert(target.input1); // value

// or in reverse
$(source).link(target);
$(target).trigger("changeData", ["age", target.age]);
alert($("[name=age]").val()); // target.age

jQuery(..).unlink() API

This removes a link previously established with link.

$(source)
    .link(target) // create link
    .unlink(target); // cancel link
Automatic unlinking

Links are cleaned up when its target or source is a DOM element that is being destroyed. For example, the following setups a link between an input and a span, then destroys the span by clearing it's parent html. The link is automatically removed.

$("#input1").link("#span1", {
    text: "input1"
});
$("#span1").parent().html("");

Revision History

* 7/23/2010 -- Completely revised the API based on feedback.
* 5/26/2010 -- Completely revised the API based on forum feedback.
* 5/01/2010 -- Corrected comments about restricted scope -- event is suppressed, not the change.
* 5/01/2010 -- Fixed glitches in comments and added info about restricted scope.
* 4/29/2010 -- Expanded on converter samples.
* 4/28/2010 -- Initial proposal published
Dedicated Server Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
  • Blog
  • Support
  • Training
  • Job Board
  • Shop
  • Contact
  • API
  • Status
  • © 2010 GitHub Inc. All rights reserved.
  • Terms of Service
  • Privacy
  • Security
  • English
  • Deutsch
  • Français
  • 日本語
  • Português (BR)
  • Русский
  • 中文
  • See all available languages

Your current locale selection: English. Choose another?

  • English
  • Afrikaans
  • Català
  • Čeština
  • Deutsch
  • Español
  • Français
  • Hrvatski
  • Indonesia
  • Italiano
  • 日本語
  • Nederlands
  • Norsk
  • Polski
  • Português (BR)
  • Русский
  • Српски
  • Svenska
  • 中文

Keyboard Shortcuts

Site wide shortcuts

s
Focus site search
?
Bring up this help dialog

Commit list

j
Move selected down
k
Move selected up
t
Open tree
p
Open parent
c or o or enter
Open commit

Pull request list

j
Move selected down
k
Move selected up
o or enter
Open issue

Issues

j
Move selected down
k
Move selected up
x
Toggle select target
o or enter
Open issue
I
Mark selected as read
U
Mark selected as unread
e
Close selected
y
Remove selected from view
c
Create issue
l
Create label
i
Back to inbox
u
Back to issues
/
Focus issues search

Network Graph

← or h
Scroll left
→ or l
Scroll right
↑ or k
Scroll up
↓ or j
Scroll down
t
Toggle visibility of head labels
shift ← or shift h
Scroll all the way left
shift → or shift l
Scroll all the way right
shift ↑ or shift k
Scroll all the way up
shift ↓ or shift j
Scroll all the way down