将事件从Pixi.js发送到Ember组件

时间:2017-01-06 06:29:18

标签: javascript ember.js pixi.js

我在Ember应用程序中运行了一个带有示例Pixi游戏的画布(我使用https://github.com/Ferdev/ember-cli-pixijs):

import PixiCanvas from 'ember-cli-pixijs/components/pixi-canvas';
import PairsGame from './pairsgame';

export default PixiCanvas.extend({

  draw() {
    const renderer = this.get('pixiRenderer');
    var game = new PairsGame()
      .init(renderer)
      .preload()
      .animate();
  },

  actions: {
    log(arg) {
      console.log(arg);
    }
  }

});

我复制的示例游戏:http://ipotaje.es/en/complete-html5-concentration-game-made-with-pixi-js-3/

如您所见,我的Pixi组件仅包含绘图/渲染逻辑,而不是游戏逻辑。它存储在外部类中,我想从中调用log动作。游戏中的文件看起来像这样:

import PIXI from 'pixi';

var PairsGame = function () {};
PairsGame.prototype.init = function (renderer)
{
  this.renderer = renderer;
  // create an empty container
  this.gameContainer = new PIXI.Container();
  const graphics = new PIXI.Graphics();
  this.gameContainer.addChild(graphics);
  // allow chain calling
  return this;
};
PairsGame.prototype.preload = function ()
{ // importing a texture atlas created with texturepacker
  var tileAtlas = ["assets/images/images.json"];
  // create a new loader
  PIXI.loader.add(tileAtlas)
            // use callback
            .once('complete', this.onLoaded.bind(this))
            //begin load
            .load();
  //allow chain calling
  return this;
};
PairsGame.prototype.animate = function ()
{
  this.renderer.render(this.gameContainer);
  requestAnimationFrame(this.animate.bind(this));
  //allow chain calling
  return this;
};

...
ET CETERA
I WOULD LIKE TO CALL THE log ACTION FROM THESE METHODS
...

现在我想在每次转弯时向我的Ember组件发送“成功”或“失败”消息,以便我可以采取某种行动(例如,只需将“成功”/“失败”记录到控制台)。有什么方法可以实现这一目标?

我尝试查看解决方案here并输入

Ember.Instrumentation.instrument("pixi.gameEvent", 'success');

在Pixi代码中,但订阅者似乎从未收到任何内容。

2 个答案:

答案 0 :(得分:1)

您可以将PixiCanvas组件上下文传递给PairsGame init方法,然后只需使用sendAction进行调用。

var game = new PairsGame()
      .init(renderer,this)
      .preload()
      .animate();
  }

在init方法中,您可以存储对PixiCanvas组件的引用,

PairsGame.prototype.init = function (renderer, pixiCanvasComp)
{
  //store component reference
  this.pixiCanvasComp = pixiCanvasComp ;
  this.renderer = renderer;
  // create an empty container
  this.gameContainer = new PIXI.Container();
  const graphics = new PIXI.Graphics();
  this.gameContainer.addChild(graphics);
  // allow chain calling
  return this;
}

使用sendAction调用log方法,

PairsGame.prototype.animate = function ()
{
  this.renderer.render(this.gameContainer);
  requestAnimationFrame(this.animate.bind(this));
  //allow chain calling
  //To call log method of PixiCanvas component,
  this.pixiCanvasComp.sendAction('log');
  return this;
}

答案 1 :(得分:0)

您需要将动作传递给您的pixi组件(https://guides.emberjs.com/v2.10.0/components/triggering-changes-with-actions/)。从本质上讲,这是一个回调,然后你可以调用你的Pixi组件内部,然后在其他地方触发其他工作......