2

我想访问 ember 操作中的事件对象以检查目标元素。这适用于 Chrome 和 Safari,但不适用于 Firefox 25.0。

我什至没有收到错误消息。如何访问 ember 操作中的事件对象,或者有没有 ember 方法可以做到这一点?

如何重现:

  1. 打开我的小提琴
  2. 单击应该打开警报框的 div 或“单击我”链接
  3. 在 chrome 和 firefox 中测试这些

HTML

  <script type="text/x-handlebars" data-template-name="application">
      <h1>Click the link in the following div</h1>
      {{outlet}}
  </script>
  <script type="text/x-handlebars" data-template-name="index">
      {{test-a}}
  </script>
  <script type="text/x-handlebars" data-template-name="components/test-a">
    <div class="index" {{action 'edit' on="click"}}>
        <a href="http://www.example.com" target="_blank">Click me</a>
    </div>
  </script>

咖啡

App = Ember.Application.create({});

App.TestAComponent = Ember.Component.extend
    actions:
        edit: ->
            if event.toElement.nodeName.toUpperCase() == 'A'
                return true # should bubble to the window but is a component
            # do something for editing here
            alert('div clicked')
            false

CSS

h1 { font-size: 1.6em; padding-bottom: 10px; }
h2 { font-size: 1.4em; }
ul { padding: 15px; font-size: 1.4em; color: green; }
.index { background-color: #666; padding: 20px; }

http://jsfiddle.net/mszrnyi/3REEj/2/

4

1 回答 1

0

一些浏览器在 中创建一个全局事件对象window.event,但这不是跨浏览器。

使用动作处理程序,您将无法正常工作。因为操作是处理浏览器事件的顶级方式。所以没有事件对象被传递,当 a{{action}}被触发时 aevent.preventDefault()被执行,所以你的链接不会打开一个新窗口。

您将需要使用click. 这是一种处理浏览器事件的低级方式,因此您将在第一个参数中获取事件对象。并且基于返回的布尔值的气泡预期行为:

 App.TestAComponent = Ember.Component.extend    
    click: (event) ->                
        if event.toElement.nodeName.toUpperCase() == 'A'
            alert('link clicked')
            return true # should bubble to the window but is a component
        # do something for editing here
        alert('div clicked')       
        false

此外,{{action 'edit' on="click"}}需要从您的components/test-a模板中删除。否则event.preventDefault()将被执行。

  <script type="text/x-handlebars" data-template-name="components/test-a">
    <div class="index">
        <a href="http://www.example.com" target="_blank">Click me</a>
    </div>
  </script>

这是更新的小提琴http://jsfiddle.net/8Ephq/

于 2013-11-11T02:55:12.217 回答