how to deal with custom events in ember.js component?

爱⌒轻易说出口 提交于 2019-12-24 00:37:56

问题


I'm new to Ember.js and I've got some problems to understand its philosophy. I know actions up, data down but in real life, lets say I have Fotorama initialized in my-gallery component (I don't know if that is ok, but I did it in didInsertElement method). This library has its own events. They could look like this in plain JS:

$('.fotorama').on('fotorama:ready', function (e, fotorama) {});

or:

$('.fotorama').on('fotorama:show', function () {});

but I feel in Ember, those should be somehow mapped into actions in component. My question is: how? I need to fire some actions (to be catched by another components or maybe a router) inside those actions. So I think it should be like this: this.sendAction('actionName', actionParams);


回答1:


You can keep component reference to call sendAction method.

didInsertElement(){
 this._super(...arguments);
 var _this=this;
 this.$('.fotorama').on('fotorama:show', function () {
  _this.sendAction('actionName', actionParams);
 });
}
willDestroyElement(){
 this._super(...arguments);
 this.$('.fotorama').off('fotorama:show')
}

If we find an better answer to this question. I will happily remove my answer.




回答2:


I have a similar problem. I need to have a third party library talk to my ember app so I registered a custom event in my ember app:

const App = Ember.Application.extend({
  customEvents: {
    foo: 'foo',
  },
});

Then triggered it from third party code:

<a href="..." onclick="$(this).trigger('foo'); return false;">

And, in a component, write the handler for that event according to the docs:

export default Ember.Component.extend({
  foo(event) {
    console.warn('event happened', event);
  },
});

See:
* https://guides.emberjs.com/v3.0.0/components/handling-events/
* https://www.emberjs.com/api/ember/release/classes/Application/properties/customEvents?anchor=customEvents

Is this answer helpful?



来源:https://stackoverflow.com/questions/41229752/how-to-deal-with-custom-events-in-ember-js-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!