Skip to content

Latest commit

 

History

History
231 lines (189 loc) · 7.94 KB

README.md

File metadata and controls

231 lines (189 loc) · 7.94 KB

jQuery Data Link plugin v1.0.0pre.

Note: This plugin is currently in beta form. It will not continue past beta, and has been superceded by JsViews, which integrates data linking with templated rendering, using JsRender templates (next-generation jQuery Templates).

See this blog post for more context on the roadmap for jQuery Templates, JsRender and JsViews...

Note: To continue to use this plugin, see tagged versions for stable Beta releases. Requires jquery version 1.4.2.

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

==================================== WARNING ====================================
Breaking change:
In jQuery 1.5, the behavior of $(plainObject).data() has been modified. In order to work against all versions of jQuery including jQuery 1.5, current builds of jquery-datalink have therefore been modified as follows:

  • The API to modify field values is now .setField( name, value ), rather than .data( name, value ). (Examples below).
  • The events associated with the modified field are now "setField" and "changeField", rather than "setData" and changeData".
Note: This plugin currently depends on jQuery version 1.4.3.
=================================================================================

Introduction

This is the official jQuery DataLink plugin. 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).

<script>
$().ready(function() {
	var person = {};
	$("form").link(person);

	$("[name=name]").val("NewValue"); // Set firstName to a value.
	alert(person.name); // NewValue

	$(person).setField("name", "NewValue");
	alert($("[name=name]").val()); // NewValue

	// ... user changes value ...
	$("form").change(function() {
		// <user typed value>
		alert(person.name);
	});
});
</script>

<form name="person">
	<label for="name">Name:</label>
	<input type="text" name="name" id="name" />
</form>

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.

<script>
$().ready(function() {
	var person = {};

	$.convertFn.round = function(value) {
		return Math.round( parseFloat( value ) );
	}

	$("#age").link(person, {
		age: {
			convert: "round"
		}
	});

	/* Once the user enters their age, the change event will fire which, in turn, will
	 * cause the round function to be called. This will then round the age up or down,
	 * set the rounded value on the object which will then cause the input field to be
	 * updated with the new value.
	 */
	$("#age").change(function() {
		alert(person.age);
	});
});
</script>

<form name="person">
	<label for="age">Age:</label>
	<input type="text" name="age" id="age" />
</form>

It is convenient to reuse converters by naming them this way. But you may also specify 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).setField("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)
	.trigger("change");

alert(target.input1); // value

// or in reverse
$(source)
	.link(target);

$(target)
	.trigger("changeField");

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("");