seajs.find 的用法与实践 #243

Closed
lifesinger opened this Issue Jul 2, 2012 · 1 comment

Projects

None yet

1 participant

@lifesinger
Member

缘由

通过 seajs 下载的模块文件,下载好后都存放在 seajs.cache 对象里:

console.dir(seajs.cache):

seajs.cache
Object
  https://a.alipayobjects.com/static/arale/base/0.9.16/attribute.js: {...}
  https://a.alipayobjects.com/static/arale/base/0.9.16/base.js: {...}
  https://a.alipayobjects.com/static/arale/class/0.9.2/class.js: {...}
  https://a.alipayobjects.com/static/arale/cookie/1.0.2/cookie.js: {...}
  https://a.alipayobjects.com/static/arale/events/0.9.1/events.js: {...}
  https://a.alipayobjects.com/static/arale/handlebars/1.0.0/handlebars.js: {...}
  https://a.alipayobjects.com/static/arale/jquery/1.7.2/jquery.js: {...}
  https://a.alipayobjects.com/static/arale/overlay/0.9.7/mask.js: {...}
  https://a.alipayobjects.com/static/arale/overlay/0.9.7/overlay.js: {...}
  ...

由于 seajs 里所有模块的接口都没暴露到全局,这样能避免污染全局环境,但同时也会导致在调试时不是很方便。

在 seajs 1.2.0 之前,需要通过下面的方式来拿到 jQuery:

seajs.use('jquery', function($) { window.$ = $ })
// use $ to debug something...

简明文档

从 seajs 1.2.0 开始,增加 seajs.find 方法,find 方法接收一个 selector 参数,selector 可以是一个字符串,也可以是一个正则,用来从 seajs.cache 里查找匹配的模块。

  • 如果没有找到匹配的模块,则返回 null
  • 如果找到一个匹配的模块,则返回该模块的接口
  • 如果找到多个匹配的模块,则返回由这些模块接口组成的数组

最佳实践

有了 seajs.find 后,调试就很方便了:

var $ = seajs.find('jquery')
// use $ to debug somethiing...

注意:理论上,seajs.find 仅用于调试,不应该出现在代码里。

@lifesinger
Member

有任何问题,欢迎留言交流。

@lifesinger lifesinger closed this Jul 2, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment