Thanks to visit codestin.com
Credit goes to github.com

Skip to content

##285 [프락시] 과제 번역 #289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions 1-js/99-js-misc/01-proxy/03-observable/solution.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
The solution consists of two parts:
해답은 크게 두 부분으로 구성됩니다.

1. Whenever `.observe(handler)` is called, we need to remember the handler somewhere, to be able to call it later. We can store handlers right in the object, using our symbol as the property key.
2. We need a proxy with `set` trap to call handlers in case of any change.
1. `.observe(handler)`이 호출될 때마다 핸들러를 어딘가에 보관해두고 나중에 호출될 수 있도록 해야 하는데, 심볼을 프로퍼티 키로 사용해 핸들러를 객체에 저장할 수 있게 해 보았습니다.
2. 변경이 있을 때마다 핸들러가 호출되도록 `set` 트랩이 있는 프락시를 만들어 보았습니다.

```js run
let handlers = Symbol('handlers');

function makeObservable(target) {
// 1. Initialize handlers store
// 1. 핸들러를 저장할 곳을 초기화합니다.
target[handlers] = [];

// Store the handler function in array for future calls
// 나중에 호출될 것을 대비하여 핸들러 함수를 배열에 저장합니다.
target.observe = function(handler) {
this[handlers].push(handler);
};

// 2. Create a proxy to handle changes
// 2. 변경을 처리할 프락시를 만듭니다.
return new Proxy(target, {
set(target, property, value, receiver) {
let success = Reflect.set(...arguments); // forward the operation to object
if (success) { // if there were no error while setting the property
// call all handlers
let success = Reflect.set(...arguments); // 동작을 객체에 전달합니다.
if (success) { // 에러 없이 프로퍼티를 제대로 설정했으면
// 모든 핸들러를 호출합니다.
target[handlers].forEach(handler => handler(property, value));
}
return success;
Expand Down