Skip to content
This repository was archived by the owner on Dec 17, 2021. It is now read-only.

Latest commit

 

History

History
74 lines (50 loc) · 2.62 KB

defineproperty.md

File metadata and controls

74 lines (50 loc) · 2.62 KB

Observer.defineProperty()

This method is used to define a property on an object or modifies an existing property. It corresponds to the JavaScript's Reflect.defineProperty() function.

Observer.defineProperty() brings the added benefit of driving observers and interceptors.

The Observer.def() function is an alias of this function and could be used interchangeably.

Syntax

// Define a property
Observer.defineProperty(obj, propertyName, propertyDescriptor);

Parameters

  • obj - an object or array.
  • propertyName - the property to define.
  • propertyDescriptor - the property descriptor as specified for Reflect.defineProperty().

Return Value

Boolean

Usage

// On an object
Observer.defineProperty(obj, 'fruit', {value:'orange'});

Usage as a Trap's defineProperty Handler

Observer.defineProperty() can be used as the "defineProperty" handler in Proxy traps.

let _obj = new Proxy(obj, {defineProperty: Observer.defineProperty});
let _arr = new Proxy(arr, {defineProperty: Observer.defineProperty});

Define operations will now be forwarded to Observer.defineProperty() and observers and interceptors that may be bound to the object will continue to respond.

Reflect.defineProperty(_obj, 'fruit', {value:'apple'});

Intercepting Observer.defineProperty()

Using Observer.intercept(), it is possible to intercept calls to Observer.defineProperty(). When a "def" operation triggers an interceptor, the interceptor will receive an event object containing the property name to define and the property descriptor.

Observer.intercept(obj, 'def', (event, recieved, next) => {
    // What we recieved...
    console.log(event.name, event.descriptor);
    // The define operation, and the return value - Boolean
    return Reflect.defineProperty(obj, event.name, event.descriptor);
});

Observer.defineProperty(obj, 'fruit', {value:'apple'});

The interceptor is expected to return true when the deletion is successful; false otherwise.

Related Methods