hagino3000's blog

平成アーカイブス (更新停止)

Ext JSのイベントバブリング

BPStudyで発表した奴。ExtJSコンポーネントに設定したイベントをバブリングさせる方法です。

やり方

バブリングさせたいイベントをもつコンポーネント

// updateイベントをバブリングさせる
this.enableBubble('update');

しておいて

getBubbleTarget : function() {
  return this.ownerCt;
}

みたいに、getBubbleTargetメソッドを実装してバブリング先を指定する。DOMのイベントバブリングと違うのは、指定したExtのコンポーネントのみにバブルする所。別に親コンポーネントじゃなくてもいい。

サンプル

コンポーネントでfireしたupdateイベントを親コンポーネントで検知してます。

ソース
/**
 * Root Panel
 */
BPSDemo.RootPanel = function(config) {
  Ext.apply(config, {
    tbar : this.createMenuBar(),
    items : []
  });
  BPSDemo.RootPanel.superclass.constructor.call(this, config);
}

Ext.extend(BPSDemo.RootPanel, Ext.Panel, {
  title : 'Parent Panetl',
  layout : 'absolute',
  bodyCssClass : 'panel_bg',

  initComponent : function() {
    BPSDemo.RootPanel.superclass.initComponent.call(this);
  },

  initEvents : function() {
    this.addEvents({
      refresh : true,
      update : true
    });
    this.on('update', function(){
      this.handleUpdate();
    }, this);
    BPSDemo.RootPanel.superclass.initEvents.call(this);
  },

  addNewPanel : function() {
    this.add(new BPSDemo.ChildPanel({}));
    this.fireEvent('update');
  },

  handleUpdate : function() {
    this.getTopToolbar().items.get(2).enable();
    this.doLayout();
  },

  createMenuBar : function() {
    return [{
      text : 'Add',
      name : 'addBtn',
      icon : 'img/add.png',
      handler : this.addNewPanel,
      scope : this
    }, {
      text : 'Delete All',
      name : 'delallBtn',
      icon : 'img/delete.png',
      handler : function() {
        this.fireEvent('refresh');
        this.fireEvent('update');
      },
      scope : this
    }, {
      text : 'Save',
      name : 'saveBtn',
      icon : 'img/disk.png',
      disabled : true,
      handler : function() {
        this.disable();
      }
    }]
  }
});


/**
 * Child Panel
 */
BPSDemo.ChildPanel = function(config) {
  Ext.apply(config, {
    x : Math.floor(Math.random() * 500),
    y : Math.floor(Math.random() * 400)
  });
  BPSDemo.ChildPanel.superclass.constructor.call(this, config);
}

Ext.extend(BPSDemo.ChildPanel, Ext.Panel, {
  height : 150,
  width : 170,
  title : 'Child Panel',
  border : true,
  frame : true,
  buttonAlign : 'center',

  initComponent : function() {
    BPSDemo.ChildPanel.superclass.initComponent.call(this);
    this.addButton({
      text : 'update',
      handler : function() {
        this.fireEvent('update');
      },
      scope : this
    });
  },

  initEvents : function() {
    this.ownerCt.on('refresh', function() {
      this.hide().destroy();
    }, this);

    this.addEvents({
      update : true
    });
    this.enableBubble('update');

    BPSDemo.ChildPanel.superclass.initEvents.call(this);
  },

  getBubbleTarget : function() {
    return this.ownerCt;
  }
});