Skip to content
⚠️ This article was written in 2019. Some content may be outdated.

JavaScript Proxy Interceptors

JavaScript Proxy interceptors are a common challenge in day-to-day development. Drawing on real projects, this article shares concrete implementation approaches and lessons learned.

Quick Start ​

Let's start with the basic usage:

javascript
export default {
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      }
    },
    loading: {
      bind(el, binding) {
        if (binding.value) {
          el.classList.add('loading')
        }
      },
      update(el, binding) {
        el.classList.toggle('loading', binding.value)
      }
    }
  }
}

This approach is clean and clear, and works well for most scenarios.

Advanced Usage ​

The core code looks like this:

javascript
import React, { Component } from 'react'

class DataList extends Component {
  state = { items: [], loading: true }

  async componentDidMount() {
    const res = await fetch('/api/items')
    const items = await res.json()
    this.setState({ items, loading: false })
  }

  render() {
    const { items, loading } = this.state
    if (loading) return <div>加载中...</div>
    return (
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    )
  }
}

In real projects you also need to consider edge cases and error handling.

Business Scenarios ​

Here is a concrete example:

javascript
import React, { Component } from 'react'

class Form extends Component {
  state = { name: '', email: '', errors: {} }

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value })
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const errors = this.validate()
    if (Object.keys(errors).length === 0) {
      this.props.onSubmit(this.state)
    } else {
      this.setState({ errors })
    }
  }

  validate() {
    const errors = {}
    if (!this.state.name) errors.name = '必填'
    if (!this.state.email.includes('@')) errors.email = '格式错误'
    return errors
  }

  render() {
    return <form onSubmit={this.handleSubmit}>...</form>
  }
}

After rolling this pattern out across the team, the results were positive and maintenance cost dropped noticeably.

Pitfall Avoidance Guide ​

We can implement it in the following way:

javascript
function deepClone(obj, map = new WeakMap()) {
  if (obj === null || typeof obj !== 'object') return obj
  if (map.has(obj)) return map.get(obj)

  const clone = Array.isArray(obj) ? [] : {}
  map.set(obj, clone)

  for (const key of Object.keys(obj)) {
    clone[key] = deepClone(obj[key], map)
  }
  return clone
}

Pay attention to the performance details in the code above and avoid unnecessary computation.

Quick Start ​

Refer to the code below for the concrete implementation:

javascript
function pLimit(concurrency) {
  const queue = []
  let active = 0

  const next = () => {
    if (active >= concurrency || queue.length === 0) return
    active++
    const { fn, resolve, reject } = queue.shift()
    fn().then(resolve, reject).finally(() => {
      active--
      next()
    })
  }

  return (fn) => new Promise((resolve, reject) => {
    queue.push({ fn, resolve, reject })
    next()
  })
}

This solution has been validated in production and runs stably.

Summary ​

  • The key to JavaScript Proxy interceptors is understanding the core concepts, not just the surface-level usage
  • Pick the right approach for the scenario in real projects
  • Consistent team conventions matter more than chasing a perfect implementation

MIT Licensed