In the three frameworks to preempt the front-end development of technology in the era, the basic framework is to achieve data binding,
Today we're going to decrypt the principle of data binding,
The principle is about a key thing, Object.prototype.__definesetter and Object.prototype.__definegetter.
MDN Address: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__
Now I'm going to implement a function that binds a value on an object with the innerHTML of the DOM element.
function bind (Ele,obj,key) { var index={ init:function () { //check for an initial value, or copy if (key in obj) { Ele.innerhtml=obj[key] } this.bind () }, bind:function () { obj.__definesetter__ (key,function (v) { ele.innerhtml=v }) obj.__definegetter__ (Key,function () { return ele.innerhtml }) }, _do:function () {} } index.init ()}
However, this function has a disadvantage, can only bind a value to an element of the innerHTML, an element can be bound to multiple values, but there is no way to bind a value of multiple DOM element properties, but can be modified to achieve, the implementation of the code will be very long, here can only be a point.
JavaScript, how to implement data binding