firefox扩展开发(九) : command元素

firefox扩展开发(九) : command元素
2008-06-11 17:02

何为command元素?从名字来看似乎和执行的命令有关,先来看个简单例子:

  1. <?xml version="1.0"?>
  2. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
  3. <window id="example-window" title="测试的窗口"
  4. xmlns:html="http://www.w3.org/1999/xhtml"
  5. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
  6. <command id="cmd_openhelp" oncommand="alert('Help!');"/>
  7. <button label="Help" command="cmd_openhelp"/>
  8. </window>

第7行就是command元素,每个command元素一般有一个id属性,唯一的标识这个command对象,为了不容易和一般元素的id相冲突,在前面加一个cmd_的前缀是个不错的办法;oncommand属性指定了和这个command对象关联的命令动作。

第8行的button元素就引用了command元素关联的命令动作,在原来的章节中,是通过oncommand属性给控件关联动作,现在只需要用command属性,并把对应的command元素id作为属性值,就可以关联到特定的动作。

看样子我们好像是兜了个大圈子,兜这个圈子有什么好处呢?

  • 首先,可以把表示命令动作的command元素单独保存在一个文件中,从而实现表示界面和表示显示的代码分离,更加容易管理。
  • 另外,如果某些按钮、菜单项、工具栏按钮执行的都是一个动作那么我们主要把他们关联到相同的command元素上即可,而不用重复写好几遍。

而且不仅如此,下面的才是关键:

  • 我们可以disable和enable一个command,如果command元素被设置成disable,那么和它关联的动作命令不会得到执行。
  • disable和enable某个command元素的同时,和这个command元素关联的控件会被自动设置成disable和enable的状态。

看个了例子:

  1. <window id="focus-example" title="测试窗口"
  2. onload="init();"
  3. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
  4. <command id="cmd_openhelp" oncommand="alert('这是帮助');"/>
  5. <button label="帮助" command="cmd_openhelp"/>
  6. <button label="还是帮助" command="cmd_openhelp"/>
  7. <button label="禁用帮助"
  8. oncommand="document.getElementById('cmd_openhelp').setAttribute('disabled','true');"/>
  9. <button label="激活帮助"
  10. oncommand="document.getElementById('cmd_openhelp').removeAttribute('disabled');"/>
  11. </window>

我们可以通过setAttribute和removeAttribute这两个方法,来设定某个command元素的disable和 enable,可以看到,如果disable了cmd_openhelp这个command,和它关联的按钮也自动变成灰色不可点击的状态:


posted @ 2011-04-07 17:53  许明吉博客  阅读(776)  评论(0编辑  收藏  举报