天天看點

CocosCreator 監聽和發射事件

監聽事件

  • 監聽的機關是節點,是以如果要設定監聽,先要擷取節點。
  • 事件監聽函數 on 可以傳四個參數完成監聽。
  • 第一個參數指明監聽的類型。
  • 第二個參數為回調函數,可以有一個參數 event ,其屬性如下表:
    CocosCreator 監聽和發射事件
  • 第三個參數是 target,用于綁定響應函數的調用者,可省略。會影響回調函數中關鍵字 this 的取值。
  • 第四個參數 useCapture(boolean)是可選參數,用于設定事件監聽為捕獲模式。詳見分發事件。
  • 除了使用 on 監聽,我們還可以使用 once 方法。once 監聽在監聽函數響應後就會關閉監聽事件。
cc.Class({
  extends: cc.Component,

  properties: {
  },

  onLoad: function () {
    this.node.on('mousedown', function ( event ) {
      console.log('Hello!');
    });
  },  
});

// 使用函數綁定
this.node.on('mousedown', function ( event ) {
  this.enabled = false;
}.bind(this));

// 使用第三個參數
this.node.on('mousedown', function (event) {
  this.enabled = false;
}, this);
           

關閉監聽

  • 當我們不再關心某個事件時,我們可以使用 off 方法關閉對應的監聽事件。需要注意的是,off 方法的 參數必須和 on 方法的參數一一對應,才能完成關閉。
cc.Class({
  extends: cc.Component,

  _sayHello: function () {
    console.log('Hello World');
  },

  onEnable: function () {
    this.node.on('foobar', this._sayHello, this);
  },

  onDisable: function () {
    this.node.off('foobar', this._sayHello, this);
  },
});
           

發射事件

  • 我們可以通過兩種方式發射事件:emit 和 dispatchEvent。兩者的差別在于,後者可以做事件傳遞。
  • emit 發射事件隻适用于本元件之内傳輸,并且在其他元件内監聽不到此事件。
  • 我們可以在 emit 函數的第二個參數開始傳遞我們的事件參數。同時,在 on 注冊的回調裡,可以擷取到對應的事件參數。最多隻支援傳遞 5 個事件參數。
cc.Class({
  extends: cc.Component,

  onLoad () {
    this.node.on('foo', function (arg1, arg2, arg3) {
      console.log(arg1, arg2, arg3);  // print 1, 2, 3
    });
  },

  start () {
    let arg1 = 1, arg2 = 2, arg3 = 3;
    // At most 5 args could be emit.
    this.node.emit('foo', arg1, arg2, arg3);
  },
});
           
  • 代碼中,‘foo’是我們自定義的事件名稱,當 emit 了一個 foo 之後,監聽 foo 的監聽器監聽到信号,執行回調函數。

派送事件

  • emit 隻能在本組鍵中進行監聽,如果我們要将資訊發送給其他元件時,就需要用到 dispatchEvent 元件。
  • 冒泡模式:将事件從事件發起節點,不斷地向上傳遞給他的父級節點,直到到達根節點或者在某個節點的響應函數中做了中斷處理 event.stopPropagation()
  • 捕獲模式:與冒泡模式相反,從最上層向下找。
this.node.dispatchEvent( new cc.Event.EventCustom('foobar', true) );

this.node.on('foobar', function (event) {
  event.stopPropagation();
});
           
  • cc.Event.EventCustom 是一個類,這裡簡單調用了構造函數,第一個參數是監聽事件的名稱,第二個參數是定義是否用冒泡模式
  • 更多參數參考:官方文檔

繼續閱讀