【问题标题】:Bubble up events from ember component从 ember 组件中冒泡事件
【发布时间】:2013-11-15 14:11:00
【问题描述】:

我创建了一个渲染 html 文本并处理点击事件的组件。

Ember 组件不会冒泡事件,但我想让对链接的点击冒泡到窗口并让浏览器处理它。

代码告诉 1000 多个单词 :-)

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/ujrZL/

【问题讨论】:

  • 使用 {{action}} 将无法正常工作。因为它将执行 evt.preventDefault()。您当前的代码是一个测试,您能分享您的意图吗?所以我可以考虑一些解决方案。谢谢。

标签: ember.js


【解决方案1】:

创建组件时,设置应使用 sendAction 传播的操作的操作名称。

{{test-a internalAction='myAction'}}

{{test-a internalAction='myAction2'}}

从组件内部

 this.sendAction('internalAction'); 

http://emberjs.jsbin.com/oPAtORO/2/edit

【讨论】:

  • 感谢您的回答!我已经尝试过 sendAction 并且它冒泡到路由但它仍然没有冒泡到浏览器。我想让浏览器处理具有所有单个属性设置的链接。如果您删除 myAction2:function(){ alert('action2'); } 它应该在新窗口/标签中打开 www.example.com。
  • 我完全按照他的方式做,但它说动作没有处理。这回真假有什么生意?我是否必须在每个潜在的冒泡动作中设置 return false ?如果我希望该操作返回其他内容怎么办?没有这方面的文档,或者非常不清楚
  • 模板上方的控制器/路由中是否定义了动作方法?
【解决方案2】:

我正在使用一种解决方法,这可能是目前唯一的方法。我不喜欢它,因为它对我来说有点味道。

咖啡脚本

actions: ->
    edit: ->
        window.open event.toElement.href, '_blank'

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 2014-08-26
    • 1970-01-01
    • 2011-10-20
    • 2011-08-23
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多