Two-way Data Binding in JavaScript

Source: Internet
Author: User

Two-way Data Binding in JavaScript

Two-way data binding is to bind the object property changes to the UI, or vice versa. In other words, if we have a user object with the name attribute, the UI will display the new name when we give the user. name a new value. Similarly, if the UI contains an input field used to enter the user name, entering a new value will change the attributes in the user object.

Many popular Client JavaScript frameworks such as Ember. js, AngularJS, and KnockoutJS all use bidirectional data binding as their top feature. However, this does not mean that it is very difficult to implement two-way data binding from scratch. Similarly, when we need two-way data binding, we can not only select one of these frameworks. The underlying idea of two-way data binding is very basic. It can be compressed into three steps:

1. We need a method to identify which UI element is bound with the corresponding attribute.

2. We need to monitor the changes in attributes and UI elements.

3. We need to spread all the changes to the bound objects and elements.

Although there are many implementation methods, the simplest and most effective way is to use the publisher-subscriber mode. The idea is simple: you can use custom data attributes to specify bindings in HTML code. All bound JavaScript objects and DOM elements will "subscribe" to a publisher object. If a JavaScript object or an HTML input field is detected to be changed at any time, we send the proxy event to the publisher-subscriber mode, this in turn broadcasts the changes and broadcasts them to all bound objects and elements.

Simple implementation with jQuery

Using jQuery to bind two-way data is very straightforward and simple, because this popular library allows us to easily subscribe to and publish DOM events and custom events:

Function DataBinder (object_id) {// use a jQuery object as a simple subscriber publisher var pubSub = jQuery ({}); // we want a data element to specify binding in the form: data-bind-<object_id> = "<property_name>" var data_attr = "bind-" + object_id, message = object_id + ": change "; // use the data-binding attribute and proxy to listen for change events on that element // so that changes can be broadcast to all associated objects jQuery (document ). on ("change", "[data-" + data_attr + "]", function (evt) {var input = jQuery (this); pubSub. trigger (message, [$ input. data (data_attr), $ input. val ()]) ;}); // PubSub transmits changes to all binding elements and sets the value of the input tag or the HTML content of other tags pubSub. on (message, function (evt, prop_name, new_val) {jQuery ("[data-" + data_attr + "=" + prop_name + "]"). each (function () {var $ bound = jQuery (this); if ($ bound. is ("input, text area, select") {$ bound. val (new_val) ;}else {response bound.html (new_val) ;}}) ;}); return pubSub ;}

In this experiment, you can simply implement a User model according to the following code:

Function User (uid) {var binder = new DataBinder (uid), user = {atttibutes :{}, // The property setter uses the data biner PubSub to publish the change set: function (attr_name, val) {this. attriures [attr_name] = val; binder. trigger (uid + ": change", [attr_name, val, this]) ;}, get: function (attr_name) {return this. attributes [attr_name] ;}, _ binder: binder }; binder. on (uid + ": change", function (vet, attr_name, new_val, initiator) {if (initiator! ==User) {user. set (attr_name, new_val );}})}

Now, no matter when we want to bind model attributes to a part of the UI, we only need to set an appropriate data attribute on the corresponding HTML element.

//JavaScriptvar user = new User(123);user.set("name","Wolfgang");//html<input type="number" data-bind-123="name" /> 

The value of the input field automatically reflects the name attribute of the user object, and vice versa. Task completed!

Do not use jQuery to create two-way Data Binding

In most of today's projects, jQuery may have been used, so you can use the previous example. But what if we go further and remove the dependency on jQuery? In fact, this is not too difficult (especially when we only support IE8 or a later version ). In the end, we need to use native JavaScript to implement a custom PubSub and observe DOM events.

Function DataBinder (object_id) {// create a simple PubSub object var pubSub = {callbacks :{}. on: function (msg, calssback) {this. callbacks [msg] = this. callbacks [msg] | []; this. callbacks [msg]. push (callback) ;}, publish: function (msg) {this. callbacks [msg] = this. callbacks [msg] | []; for (var I = 0, len = this. callbacks [msg]. length; I <lenli ++) {this. callbacks [msg] [I]. apply (this, arguments) ;}}, data_attr = "data -Bind-"+ object_id, message = object_id +": change ", changeHandler = function (evt) {var target = evt.tar get | evt. srcElemnt, // IE8 compatible with prop_name = target. getAttribute (data_attr); if (prop_name & prop_name! = "") {PubSub. publish (message, prop_name, target. value) ;}}; // listen to the change event and proxy to PubSub if (document. addEventListener) {document. addEventListener ("change", changeHandler, false);} else {// IE8 uses attachEvent instead of addEventListener document. attachEvent ("onchange", changeHandler);} // PubSub transmits the change to all bound elements pubSub. on (message, function (vet, prop_name, new) _ val) {var elements = document. querySelectorAll ("[" + data_attr + "=" + prop_name + "]"), tah_name; for (var I = 0, len = elements. length; I <len; I ++) {tag_name = elements [I]. tagName. toLowerCase (); if (tag_name = "input" | tag_name = "textarea" | tag_name = "select") {elements [I]. value = new_val;} else {elements [I]. innerHTML = new_val ;}}); return pubSub ;}

The model can be kept consistent with the diligent example. In addition to calling the jQuery trigger method in the seter, it needs to be implemented by calling a custom PubSub publish method:

// Function User (uid ){//... user = {//... set: function (attr_name, val) {this. attribute [attr_name] = val; // use the "publish" method binder. publish (uid + ": change", attr_name, val, this );}}//...}

Again, we use native JavaScript code to achieve the same results, instead of using a bloated JavaScript framework.

Easy two way data-binding in JavaScript, original address http://www.lucaongaro.eu/blog/2012/12/02/easy-two-way-data-binding-in-javascript/

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.