Home  >  Article  >  Web Front-end  >  Anatomical analysis of Hongmeng system’s JavaScript framework

Anatomical analysis of Hongmeng system’s JavaScript framework

coldplay.xixi
coldplay.xixiforward
2020-09-17 17:04:122538browse

Anatomical analysis of Hongmeng system’s JavaScript framework

Relevant learning recommendations: javascript

I have introduced Hongmeng’s Javascript framework in the previous article. Finally, the JS warehouse was compiled and passed. During the process, I encountered many pitfalls and contributed several PRs to Hongmeng. Today we will analyze the JS framework in Hongmeng system line by line.

All the codes in this article are based on the latest version of Hongmeng (version 677ed06, submission date 2020-09-10).

Hongmeng system uses JavaScript to develop GUI, which is a model similar to WeChat applets and light applications. In this MVVM model, V is actually assumed by C. The JavaScript code is just the ViewModel layer within it.

The Hongmeng JS framework has zero dependencies and only uses some npm packages during the development and packaging process. The packaged code does not depend on any npm package. Let’s first take a look at what the JS code written using the Hongmeng JS framework looks like.

export default {
  data() {    return { count: 1 };
  },
  increase() {
    ++this.count;
  },
  decrease() {
    --this.count;
  },
}复制代码

If I didn’t tell you this is Hongmeng, you would even think it is vue or a small program. If JS is used alone (out of Hongmeng system), the code is as follows:

const vm = new ViewModel({
  data() {    return { count: 1 };
  },
  increase() {
    ++this.count;
  },
  decrease() {
    --this.count;
  },
});console.log(vm.count); // 1vm.increase();console.log(vm.count); // 2vm.decrease();console.log(vm.count); // 1复制代码

All the JS code in the warehouse implements a responsive system, acting as the ViewModel in MVVM.

Let’s analyze it line by line.

There are 4 directories in the src directory, with a total of 8 files. 1 of them is a unit test. There is also 1 performance analysis. Excluding the 2 index.js files, there are 4 useful files in total. It is also the focus of this analysis.

src
├── __test__
│   └── index.test.js
├── core
│   └── index.js
├── index.js
├── observer
│   ├── index.js
│   ├── observer.js
│   ├── subject.js
│   └── utils.js
└── profiler
    └── index.js复制代码

The first is the entry file, src/index.js, which has only 2 lines of code:

import { ViewModel } from './core';export default ViewModel;复制代码

It is actually re-exporting.

Another similar file is src/observer/index.js, which is also 2 lines of code:

export { Observer } from './observer';export { Subject } from './subject';复制代码

observer and subject implement an observer pattern. subject is the subject, that is, the person being observed. observer is an observer. When there are any changes in the subject, the observer needs to be actively notified. This is responsiveness.

Both these two files use src/observer/utils.js, so let’s analyze the utils file first. Divided into 3 parts.

The first part

export const ObserverStack = {  stack: [],
  push(observer) {    this.stack.push(observer);
  },
  pop() {    return this.stack.pop();
  },
  top() {    return this.stack[this.stack.length - 1];
  }
};复制代码

Firstly, a stack is defined to store observers. It follows the last-in-first-out principle and uses stack internally. Array to store.

  • Push operation push, like the push function of the array, puts an observer observer on the top of the stack.
  • Pop operation pop, like the pop function of the array, deletes the observer on the top of the stack and returns the deleted observer.
  • Get the top element of the stack top is different from the pop operation. top takes out the top element of the stack but does not delete it.

Part 2

export const SYMBOL_OBSERVABLE = '__ob__';export const canObserve = target => typeof target === 'object';复制代码

defines a string constant SYMBOL_OBSERVABLE. For convenience later use.

defines a function canObserve, whether the target can be observed. Only objects can be observed, so use typeof to determine the type of the target. Wait, something seems wrong. If target is null, the function will also return true. If null is not observable, then this is a bug. (While writing this I had already filed a PR asking if this behavior was expected).

Part 3

export const defineProp = (target, key, value) => {  Object.defineProperty(target, key, { enumerable: false, value });
};复制代码

There is nothing to explain, it is Object.defineProperty The code is too long, define a function to avoid the code repeat.

Let’s analyze the observer src/observer/observer.js, divided into 4 parts.

Part One

export function Observer(context, getter, callback, meta) {  this._ctx = context;  this._getter = getter;  this._fn = callback;  this._meta = meta;  this._lastValue = this._get();
}复制代码

Constructor. Accepts 4 parameters.

context The context in which the current observer is located, type is ViewModel. When the third parameter callback is called, the this of the function is this context.

getter Type is a function used to get the value of a property.

callback type is a function, a callback function that is executed when a certain value changes.

meta Metadata. Observer does not pay attention to meta metadata.

In the last line of the constructor, this._lastValue = this._get(). Let’s analyze the _get function.

Part 2

Observer.prototype._get = function() {  try {
    ObserverStack.push(this);    return this._getter.call(this._ctx);
  } finally {
    ObserverStack.pop();
  }
};复制代码

ObserverStack is the stack analyzed above to store all observers. Push the current observer onto the stack and obtain the current value through _getter. Combined with the constructor of the first part, this value is stored in the _lastValue attribute.

After executing this process, the observer has been initialized.

the third part

Observer.prototype.update = function() {  const lastValue = this._lastValue;  const nextValue = this._get();  const context = this._ctx;  const meta = this._meta;  if (nextValue !== lastValue || canObserve(nextValue)) {    this._fn.call(context, nextValue, lastValue, meta);    this._lastValue = nextValue;
  }
};复制代码

这部分实现了数据更新时的脏检查(Dirty checking)机制。比较更新后的值和当前值,如果不同,那么就执行回调函数。如果这个回调函数是渲染 UI,那么则可以实现按需渲染。如果值相同,那么再检查设置的新值是否可以被观察,再决定到底要不要执行回调函数。

第四部分

Observer.prototype.subscribe = function(subject, key) {  const detach = subject.attach(key, this);  if (typeof detach !== 'function') {    return;
  }  if (!this._detaches) {    this._detaches = [];
  }  this._detaches.push(detach);
};

Observer.prototype.unsubscribe = function() {  const detaches = this._detaches;  if (!detaches) {    return;
  }  while (detaches.length) {
    detaches.pop()();
  }
};复制代码

订阅与取消订阅。

我们前面经常说观察者和被观察者。对于观察者模式其实还有另一种说法,叫订阅/发布模式。而这部分代码则实现了对主题(subject)的订阅。

先调用主题的 attach 方法进行订阅。如果订阅成功,subject.attach 方法会返回一个函数,当调用这个函数就会取消订阅。为了将来能够取消订阅,这个返回值必需保存起来。

subject 的实现很多人应该已经猜到了。观察者订阅了 subject,那么 subject 需要做的就是,当数据变化时即使通知观察者。subject 如何知道数据发生了变化呢,机制和 vue2 一样,使用 Object.defineProperty 做属性劫持。

下面再来分析观察者 src/observer/subject.js,分 7 部分。

第一部分

export function Subject(target) {  const subject = this;
  subject._hijacking = true;
  defineProp(target, SYMBOL_OBSERVABLE, subject);  if (Array.isArray(target)) {
    hijackArray(target);
  }  Object.keys(target).forEach(key => hijack(target, key, target[key]));
}复制代码

构造函数。基本没什么难点。设置 _hijacking 属性为 true,用来标示这个对象已经被劫持了。Object.keys 通过遍历来劫持每个属性。如果是数组,则调用 hijackArray

第二部分

两个静态方法。

Subject.of = function(target) {  if (!target || !canObserve(target)) {    return target;
  }  if (target[SYMBOL_OBSERVABLE]) {    return target[SYMBOL_OBSERVABLE];
  }  return new Subject(target);
};

Subject.is = function(target) {  return target && target._hijacking;
};复制代码

Subject 的构造函数并不直接被外部调用,而是封装到了 Subject.of 静态方法中。

如果目标不能被观察,那么直接返回目标。

如果 target[SYMBOL_OBSERVABLE] 不是 undefined,说明目标已经被初始化过了。

否则,调用构造函数初始化 Subject。

Subject.is 则用来判断目标是否被劫持过了。

第三部分

Subject.prototype.attach = function(key, observer) {  if (typeof key === 'undefined' || !observer) {    return;
  }  if (!this._obsMap) {    this._obsMap = {};
  }  if (!this._obsMap[key]) {    this._obsMap[key] = [];
  }  const observers = this._obsMap[key];  if (observers.indexOf(observer) < 0) {
    observers.push(observer);    return function() {
      observers.splice(observers.indexOf(observer), 1);
    };
  }
};复制代码

这个方法很眼熟,对,就是上文的 Observer.prototype.subscribe 中调用的。作用是某个观察者用来订阅主题。而这个方法则是“主题是怎么订阅的”。

观察者维护这一个主题的哈希表 _obsMap。哈希表的 key 是需要订阅的 key。比如某个观察者订阅了 name 属性的变化,而另一个观察者订阅了 age 属性的变化。而且属性的变化还可以被多个观察者同时订阅,因此哈希表存储的值是一个数组,数据的每个元素都是一个观察者。

第四部分

Subject.prototype.notify = function(key) {  if (    typeof key === &#39;undefined&#39; ||
    !this._obsMap ||
    !this._obsMap[key]
  ) {    return;
  }  this._obsMap[key].forEach(observer => observer.update());
};复制代码

当属性发生变化是,通知订阅了此属性的观察者们。遍历每个观察者,并调用观察者的 update 方法。我们上文中也提到了,脏检查就是在这个方法内完成的。

第五部分

Subject.prototype.setParent = function(parent, key) {  this._parent = parent;  this._key = key;
};

Subject.prototype.notifyParent = function() {  this._parent && this._parent.notify(this._key);
};复制代码

这部分是用来处理属性嵌套(nested object)的问题的。就是类似这种对象:{ user: { name: 'JJC' } }

第六部分

function hijack(target, key, cache) {  const subject = target[SYMBOL_OBSERVABLE];  Object.defineProperty(target, key, {    enumerable: true,
    get() {      const observer = ObserverStack.top();      if (observer) {
        observer.subscribe(subject, key);
      }      const subSubject = Subject.of(cache);      if (Subject.is(subSubject)) {
        subSubject.setParent(subject, key);
      }      return cache;
    },
    set(value) {
      cache = value;
      subject.notify(key);
    }
  });
}复制代码

这一部分展示了如何使用 Object.defineProperty 进行属性劫持。当设置属性时,会调用 set(value),设置新的值,然后调用 subject 的 notify 方法。这里并不进行任何检查,只要设置了属性就会调用,即使属性的新值和旧值一样。notify 会通知所有的观察者。

第七部分

劫持数组方法。

const ObservedMethods = {  PUSH: &#39;push&#39;,  POP: &#39;pop&#39;,  UNSHIFT: &#39;unshift&#39;,  SHIFT: &#39;shift&#39;,  SPLICE: &#39;splice&#39;,  REVERSE: &#39;reverse&#39;};const OBSERVED_METHODS = Object.keys(ObservedMethods).map(    key => ObservedMethods[key]
);复制代码

ObservedMethods 定义了需要劫持的数组函数。前面大写的用来做 key,后面小写的是需要劫持的方法。

function hijackArray(target) {
  OBSERVED_METHODS.forEach(key => {    const originalMethod = target[key];

    defineProp(target, key, function() {      const args = Array.prototype.slice.call(arguments);
      originalMethod.apply(this, args);      let inserted;      if (ObservedMethods.PUSH === key || ObservedMethods.UNSHIFT === key) {
        inserted = args;
      } else if (ObservedMethods.SPLICE) {
        inserted = args.slice(2);
      }      if (inserted && inserted.length) {
        inserted.forEach(Subject.of);
      }      const subject = target[SYMBOL_OBSERVABLE];      if (subject) {
        subject.notifyParent();
      }
    });
  });
}复制代码

数组的劫持和对象不同,不能使用 Object.defineProperty

我们需要劫持 6 个数组方法。分别是头部添加、头部删除、尾部添加、尾部删除、替换/删除某几项、数组反转。

通过重写数组方法实现了数组的劫持。但是这里有一个需要注意的地方,数据的每一个元素都是被观察过的,但是当在数组中添加了新元素时,这些元素还没有被观察。因此代码中还需要判断当前的方法如果是 pushunshiftsplice,那么需要将新的元素放入观察者队列中。

另外两个文件分别是单元测试和性能分析,这里就不再分析了。

想了解更多编程学习,敬请关注php培训栏目!

The above is the detailed content of Anatomical analysis of Hongmeng system’s JavaScript framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete