search
HomeWeb Front-endJS TutorialUse Object.defineProperty to implement simple js two-way binding_javascript skills

Origin

A few days ago I was looking at the implementation of some popular mini mvvm frameworks (such as lighter frameworks such as avalon.js and vue.js, rather than heavier frameworks such as Angularjs and Emberjs). Modern popular mvvm frameworks generally remove two-ways data binding as a selling point of the framework itself (Ember.js does not seem to support two-way data binding.), and each framework has two-way data binding. The implementation methods of binding are not consistent. For example, Anguarjs uses dirty checking internally, while the essence of the internal implementation method of avalon.js is to set property accessors.

I am not going to discuss the specific implementation of two-way data binding by each framework here. I will only talk about several common methods of implementing two-way data binding on the front end, and focus on the technology selection of avalon.js to implement two-way data binding. type.

General implementation of two-way data binding

First, let’s talk about what front-end two-way data binding is. To put it simply, it is the controller layer of the framework (the controller layer here is a general term, which can be understood as the middleware that controls the view behavior and contacts the model layer) and the UI presentation layer (view layer) to establish a two-way data channel. . When a change occurs in either layer, the other layer will automatically make corresponding changes immediately (or seemingly immediately).

Generally speaking, to achieve this two-way data binding relationship (the association process between the controller layer and the display layer), there are currently three ways on the front end,

1.Dirty Check

2. Observation mechanism

3. Encapsulated property accessor

Dirty Check

We say that the technical implementation of two-way data binding in Angularjs (here specifically refers to the AngularJS 1.x.x version, not the AngularJS 2.x.x version) is dirty checking. The general principle is that Angularjs will maintain a sequence internally to combine all required The monitored attributes are placed in this sequence. When certain events occur (note that this is not scheduled but triggered by certain special events), Angularjs will call the $digest method. The internal logic of this method is to traverse All watchers compare the monitored attributes to see if their attribute values ​​have changed before and after the method is called. If they change, the corresponding handler is called. There are many articles on the Internet that analyze the implementation principles of Angularjs two-way data binding, such as this article, and this article, and so on.

The disadvantage of this method is obvious. Traversing and training watchers is very performance-consuming, especially when the number of monitors on a single page reaches an order of magnitude.

Observation mechanism

The blogger had a reprinted and translated article before. The data binding changes brought about by Object.observe() are about using the Object.observe method in ECMAScript7 to monitor and observe objects (or their properties). Once they are When a change occurs, the corresponding handler will be executed.

This is currently the most perfect way to monitor attribute data changes. The language (browser) supports it natively. There is nothing better than this. The only regret is that the current breadth of support is not enough and needs to be fully promoted.

Encapsulated property accessor

There is a concept of magic method in PHP, such as the __get() and __set() methods in PHP. There is a similar concept in JavaScript, but it is not called a magic method, but an accessor. Let’s take a look at a sample code,

var data = {
name: "erik",
getName: function() {
return this.name;
},
setName: function(name) {
this.name = name;
}
};

从上面的代码中我们可以管中窥豹,比如 data 中的 getName() 和 setName() 方法,我们可以简单的将其看成 data.name 的访问器(或者叫做 存取器 )。

其实,针对上述的代码,更加严格一点的话,不允许直接访问 data.name 属性,所有对 data.name 的读写都必须通过 data.getName() 和 data.setName() 方法。所以,想象一下,一旦某个属性不允许对其进行直接读写,而必须是通过访问器进行读写时,那么我当然通过重写属性的访问器方法来做一些额外的情,比如属性值变更监控。使用属性访问器来做数据双向绑定的原理就是在此。

这种方法当然也有弊端,最突出的就是每添加一个属性监控,都必须为这个属性添加对应访问器方法,否则这个属性的变更就无法捕获。

Object.defineProperty 方法

国产mvvm框架avalon.js实现数据双向绑定的原理就是属性访问器。不过它当然不会像上述示例代码一样原始。它使用了ECMAScript5.1(ECMA-262)中定义的标准属性 Object.defineProperty 方法。针对国内行情,部分还不支持 Object.defineProperty 低级浏览器采用VBScript作了完美兼容,不像其他的mvvm框架已经逐渐放弃对低端浏览器的支持。

我们先来MDN上对 Object.defineProperty 方法的定义,

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

意义很明确, Object.defineProperty 方法提供了一种直接的方式来定义对象属性或者修改已有对象属性。其方法原型如下,

Object.defineProperty(obj, prop, descriptor)

其中,

obj ,待修改的对象
prop ,带修改的属性名称
descriptor ,待修改属性的相关描述
descriptor 要求传入一个对象,其默认值如下,

/**
* @{param} descriptor
*/
{
configurable: false,
enumerable: false,
writable: false,
value: null,
set: undefined,
get: undefined
}

configurable ,属性是否可配置。可配置的含义包括:是否可以删除属性( delete ),是否可以修改属性的 writable 、 enumerable 、 configurable 属性。

enumerable ,属性是否可枚举。可枚举的含义包括:是否可以通过 for...in 遍历到,是否可以通过 Object.keys() 方法获取属性名称。

writable ,属性是否可重写。可重写的含义包括:是否可以对属性进行重新赋值。

value ,属性的默认值。

set ,属性的重写器(暂且这么叫)。一旦属性被重新赋值,此方法被自动调用。

get ,属性的读取器(暂且这么叫)。一旦属性被访问读取,此方法被自动调用。

下面来一段示例代码,

var o = {};
Object.defineProperty(o, 'name', {
value: 'erik'
});
console.log(Object.getOwnPropertyDescriptor(o, 'name')); // Object {value: "erik", writable: false, enumerable: false, configurable: false}
Object.defineProperty(o, 'age', {
value: 26,
configurable: true,
writable: true
});
console.log(o.age); // 26
o.age = 18;
console.log(o.age); // 18. 因为age属性是可重写的
console.log(Object.keys(o)); // []. name和age属性都不是可枚举的
Object.defineProperty(o, 'sex', {
value: 'male',
writable: false
});
o.sex = 'female'; // 这里的赋值其实是不起作用的
console.log(o.sex); // 'male';
delete o.sex; // false, 属性删除的动作也是无效的

经过上述的示例,正常情况下 Object.definePropert() 的使用都是比较简单的。

不过还是有一点需要额外注意一下, Object.defineProperty() 方法设置属性时,属性不能同时声明访问器属性( set 和 get )和 writable 或者 value 属性。 意思就是,某个属性设置了 writable 或者 value 属性,那么这个属性就不能声明 get 和 set 了,反之亦然。

因为 Object.defineProperty() 在声明一个属性时,不允许同一个属性出现两种以上存取访问控制。

示例代码,

var o = {},
myName = 'erik';
Object.defineProperty(o, 'name', {
value: myName,
set: function(name) {
myName = name;
},
get: function() {
return myName;
}
});

上面的代码看起来貌似是没有什么问题,但是真正执行时会报错,报错如下,

TypeError: Invalid property. A property cannot both have accessors and be writable or have a value, #<Object>

因为这里的 name 属性同时声明了 value 特性和 set 及 get 特性,这两者提供了两种对 name 属性的读写控制。这里如果不声明 value 特性,而是声明 writable 特性,结果也是一样的,同样会报错。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor