You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery命名空间绑定后Resize事件未触发的技术问题

问题分析与修复方案

嘿,我一眼就发现问题出在哪了——你把resize事件绑定到了document对象上,但浏览器的resize事件只会触发在window对象上,所以你的_onDocumentResize回调永远不会被执行!

核心错误点

$(window.document).on('resize.myView', ...) 这行代码是错的,resize事件不属于document,而是专属window对象的事件。

修复步骤

1. 修正resize事件的绑定对象

把resize事件绑定到window上,而不是document:

$(window).on('resize.myView', this._onDocumentResize.bind(this));

2. 完善_cleanup方法

你之前的_cleanup方法没写完,这里要确保正确解绑所有带命名空间的事件,同时别忘了解绑clean按钮的click事件:

_cleanup() {
  // 解绑document上的click.myView事件
  $(window.document).off('click.myView');
  // 解绑window上的resize.myView事件
  $(window).off('resize.myView');
  // 解绑clean按钮的click事件
  $('#clean').off('click', this._cleanup.bind(this));
}

3. 补充_onDocumentResize的实现(示例)

你没给出这个方法的具体逻辑,这里补上一个简单的示例,方便验证:

_onDocumentResize() {
  console.log(`Window resized: ${$(window).width()}x${$(window).height()}`);
}

完整修正后的代码

class MyView {
  constructor() {
    // 绑定document的click事件(这部分是正确的)
    $(window.document).on('click.myView', this._onDocumentClick.bind(this));
    // 修正:绑定window的resize事件
    $(window).on('resize.myView', this._onDocumentResize.bind(this));
    // 绑定clean按钮的清理事件
    $('#clean').on('click', this._cleanup.bind(this));
  }

  _onDocumentClick() {
    console.log("Mouse Clicked");
  }

  _onDocumentResize() {
    console.log(`Window resized: ${$(window).width()}x${$(window).height()}`);
  }

  _cleanup() {
    // 安全解绑带命名空间的事件,不会影响其他同类型事件
    $(window.document).off('click.myView');
    $(window).off('resize.myView');
    // 解绑按钮事件
    $('#clean').off('click', this._cleanup.bind(this));
    console.log("Cleanup done - all events unbound");
  }
}

额外说明

使用命名空间(比如.myView)的好处就是,你可以精准解绑自己绑定的事件,不会影响其他代码中绑定的click或resize事件,这正是你想要的“安全解绑”效果。

内容的提问来源于stack exchange,提问作者Shahar Shokrani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:32:19