2013-05-11 49 views
14

我正在更新个人项目,其中使用了ember.js 0.9.x版本。我们如何才能在余烬的行动中获得原始事件

因此,新版本发布了,并且我遇到了一个与ember操作相关的问题。

我有以下的html代码:

<li><a href="#" id="startApp" {{action activateView target="view"}}> Home</a> <span class="divider">|</span></li> 

哪里,当我点击它调用这个函数activateView:

activateView: function(event, context) { 
    console.log(event);    
} 

但该事件和上下文是不确定的。我已经尝试过this.context,它返回undefined。

其主要思想是当用户点击时获取链接的id。

我知道路线和车把助手链接,但我真的需要一个ID为其他的事情,

你能帮助我吗?

谢谢

回答

7

使用操作帮助程序不会传递事件。如果你真的想事件对象,你需要定义一个视图,并使用click事件:

App.MyLink = Em.View.extend({ 
    click: function(e) { 
    } 
}); 

然后:

<li>{{view App.MyLink}}</li> 

,但需要访问DOM事件是一种罕见的情况下,由于您可以将参数传递给{{action}}。你的情况:

<li><a href="#" id="startApp" {{action activateView "startApp" target="view"}}> Home</a> <span class="divider">|</span></li> 

和事件:

activateView: function(id) { 
    console.log(id);    
} 
+0

谢谢你的帮助。尝试解决这个问题需要几个小时,最终解决方案非常简单。 – 2013-05-12 10:48:39

+0

不客气,很高兴它的工作! – 2013-05-12 13:15:24

+5

还有一个事件不仅仅是DOM元素。我明白,不要在动作中访问事件,或者如果我真的需要设置自己的自定义处理程序,这是更好的做法。但是有没有一些后门可以访问这个活动?基本上没有人真正回答OP的问题。 – 2014-02-28 15:49:06

2

需要ID传递给你的函数,像这样把它在视图访问,你可以沿着你想要什么都通,但在你的例子这应该这样做

HTML

<li><a href="#" id="startApp" {{action activateView "startApp" target="view"}}> Home</a> <span class="divider">|</span></li> 

那么你可以访问你传递的ID或什么都,在视图

JS

... 
activateView: function(data){ 
    console.log(data); // should be the ID "startApp" 
} 
... 
+0

谢谢你的帮助。尝试解决这个问题需要几个小时,最终解决方案非常简单。 – 2013-05-12 10:48:21

+0

欢迎:) – intuitivepixel 2013-05-12 10:50:22

11

在余烬2 ...

里面你的行动,你总是有机会获得具有DOM元素的Javascript event对象,例如

actions: { 
    myAction() { 
     console.log(event.target) // prints the DOM node reference 
    } 
} 
+0

非常感谢这个 – agent47 2017-01-18 00:31:57

+4

对我来说,这似乎并不适用于Firefox。我收到一个错误,指出:'ReferenceError:event is not defined'。 例如:https://jsfiddle.net/6fra6cL4/ – 2017-03-01 22:58:02

+0

这是在Ember文档中的任何地方提及的吗?我似乎无法找到它。 – 2017-05-12 14:23:33

0

有两种方法可以收到行动event对象,

1.如果您使用的组件,那么你可以定义任何事件的这个名单中组件中的名称以及旨在接收本机事件对象的名称。例如,{{my-button model=model}}

export default Ember.Component.extend({ 
click(event){ 
    //oncliking on this componen will trigger this function 
    return true; //to bubble this event up 
} 
}) 

2.如果您使用的是像按钮HTML标记,那么你需要指定一个(封闭)的行动内联事件处理程序。

{{#each item as |model|}} 
     <button onclick={{action 'toggle' model}}>{{model.title}}</button> 
{{/each}} 

在动作哈希切换函数将始终接收本机浏览器事件对象作为最后一个参数。

actions:{ 
toggle(model,event){ 

} 
} 

在下面的格式,操作切换不会收到event对象,

  • <button {{action 'toggle'}}>{{model.title}}</button>
  • 输入助手如{{input key-press="toggle"{{text-area key-press="toggle"

在灰烬导https://guides.emberjs.com/v2.12.0/components/handling-events/#toc_sending-actions解释真的很好