Data binding: View-to-model

Source: Internet
Author: User

Previous data binding: Model-to-view is a simple introduction to binding from model to view, and we want more than that, and we want the data model to be affected when the view changes. The most applied scenario should be the form, so that changing the view changes the data to be submitted so that our workload can be greatly reduced.

event, or event

When a user is working in a form, the event is naturally triggered by a keyboard or mouse, and we capture these events and manipulate the model in the event handler function.

In general, for DOM events, the framework uses custom directives, such as angular with ng-, and regular with on-.

However, sometimes the view change is not triggered by the event, or the user in the JS code to update a part of the view, such as: Input.setattribute ('value', ' ") , then we also have to monitor and change the data model.

In general, this pattern is handled by subscription/release (PUBSUB), which is the custom event, and the principle is probably:

In advance, a series of listener functions for a custom event name are push into the array, and when the Fire/trigger/emit (true name) notification is received, the listener functions are all executed.

varEvents =(function () {varTopics = {}; varHOP =Topics.hasownproperty; return{subscribe:function (topic, listener) {//Create The topic ' s object if not yet created      if(!hop.call (topics, topic)) topics[topic] = []; //ADD the listener to queue      varindex = Topics[topic].push (listener)-1; //provide handle back for removal of topic      return{remove:function () {delete Topics[topic][index];    }      }; }, Publish:function (topic, info) {//If The topic doesn ' t exist, or there ' s no listeners in queue, just leave      if(!hop.call (topics, topic))return; //Cycle through topics queue, fire!Topics[topic].foreach (function (item) {Item (Info! = undefined?info: {});    }); }  };}) ();

The simple implementation comes from Pub/sub JavaScript Object. There are more subtle implementations: PUBSUBJS.

Dirty Check

In data binding: the model to the end of the view, the force dirty check two-way binding example. In general, the framework will automatically enter the $degist phase, but in some special cases, the user can also be done manually by means of the framework exposure, as regular provides the $update method.

Mutationobserver

The exciting time has come:

MutationObserverProvides developers with the ability to respond appropriately when a DOM tree changes in a range.

And the support situation is still passable:

Through Mutationobserver, we can get to the DOM tree changes, whether you are the event or the inexplicable change ....

The usage is also extremely simple:

Set the behavior to monitor
varObserveconfig ={attributes:true, Childlist:true, Characterdata:true, Attributeoldvalue:true, subtree:true, attributefilter:['value'] }varmutationobserver = window. Mutationobserver | | Window. Webkitmutationobserver | |window. Mozmutationobserver;varObserver =NewMutationobserver (function (mutations) {//) triggers a secondary method whenever there is a change, looping through the changed record Mutations.foreach (function (record, i) { Console.log (record); }); O Bserver.observe (Element, observeconfig);

In this case, we can do whatever we like in the listening function.

However, there is a problem here, for form elements, such as the input box, enter or delete some characters, and does not trigger the listening method, like this: Input.value = XXX does not trigger the operation.

This is because Mutationobserver only listens to changes in the DOM book, that is, nodes and attributes, while input or delete and direct value does not cause changes in the DOM tree, printing some input.getattribute (' value You find that the value doesn't change at all!!!

It's all about asking for help.

Input.onkeyup = function (e) {    var target = e.target;    Target.setattribute ('value', target.value);}

This will be OK.

In fact, ie in the early implementation of the Onpropertychange event, but only one of the standard oninput can listen to value values, but this also provides a way of thinking about compatibility.

DOM Attributes on the prototype chain

Just finished writing this post, accidentally saw an article: DOM Attributes now on the prototype chain, Chinese translation here.

Chrome in IE, Firefox also support the prototype chain DOM, I think this should also be the view-to-model binding way, we can give the DOM node custom properties, and then like this:

Object.defineproperty (Htmldivelement.prototype, "issupercontenteditable", {    function  Returntrue;},    function/*/*  },});

In the setter we can do what we want to do. You can easily implement commands like **-model.

<type= "text"  z-model= "">
var data = {}; var input = document.queryselector (' input '' Z-model ', {    function()} {         return data.name;    },     function (n) {        = n;         = n;    }});

And then a simple change, two-way binding also has ...

vardata = {};var_name = ' init ';varinput = document.queryselector (' input '); Object.defineproperty (data,' Name ', {get:function() {        return_name; }, set:function(n) {_name=N; Input.value=N; }}); Object.defineproperty (input,' Z-model ', {get:function() {        returnData.name; }, set:function(n) {data.name=N; Input.value=N; }});

Resources:

Component Events

Viewer of the DOM world

MDN Mutationobserver

Test whether Domattrmodified is supported

Data binding: View-to-model

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.