为什么我的按钮组件提交它所在的表单?

时间:2022-11-24 09:04:18

If I put a button inside a form and click on it, only the button-click event is triggered.

如果我在表单中放置一个按钮并单击它,则只会触发按钮单击事件。

But if I build a button component "my-button", replace the button with "my-button" and click on it again, it triggers the button click event but also submits the form.

但是,如果我构建一个按钮组件“my-button”,用“my-button”替换该按钮并再次单击它,它会触发按钮单击事件,但也会提交表单。

Is it supposed to behave that way? How do I make my component not submit the form?

它应该表现得那样吗?如何让我的组件不提交表单?

App = Ember.Application.create();

App.ApplicationController = Ember.Controller.extend({
  actions: {
    clicked: function() {
      alert('click');
    },
    submitted: function() {
      alert('submit');
    }
  }
});

App.MyButtonComponent = Ember.Component.extend({
  tagName: "button",
  click: function() {
    this.sendAction();
  }
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="http://builds.emberjs.com/tags/v1.11.1/ember-template-compiler.js"></script><script src="http://builds.emberjs.com/tags/v1.11.1/ember.debug.js"></script>

<script type="text/x-handlebars">
    <form {{action "submitted" on="submit" }}>
        {{my-button action="clicked"}}
        <button {{action "clicked"}}>button</button>
    </form>
</script>

<script type="text/x-handlebars" data-template-name="components/my-button">
    my-button
</script>

I also created a JS Bin. Any click event logs “click” to the console and a form submit logs “submit” into the browser console.

我还创建了一个JS Bin。任何单击事件都会“点击”到控制台,表单提交会将“提交”记录到浏览器控制台中。

1 个解决方案

#1


1  

The problem is that you aren't specifying the type of button, and by default the button type is "submit", which then submits your action. You can change this by specifying the button type in your component.

问题是你没有指定按钮的类型,默认情况下按钮类型是“提交”,然后提交你的动作。您可以通过在组件中指定按钮类型来更改此设置。

App.MyButtonComponent = Ember.Component.extend({
  tagName: "button",

  attributeBindings: ['type'],
  click: function(){
    this.sendAction();
  }
});

Now, when specifying your form, you can tell your component what type of button it should be.

现在,在指定表单时,您可以告诉组件它应该是什么类型的按钮。

inside form: {{my-button action="clicked" type="button"}}

http://jsbin.com/zutacipido/2/edit

http://jsbin.com/zutacipido/2/edit

#1


1  

The problem is that you aren't specifying the type of button, and by default the button type is "submit", which then submits your action. You can change this by specifying the button type in your component.

问题是你没有指定按钮的类型,默认情况下按钮类型是“提交”,然后提交你的动作。您可以通过在组件中指定按钮类型来更改此设置。

App.MyButtonComponent = Ember.Component.extend({
  tagName: "button",

  attributeBindings: ['type'],
  click: function(){
    this.sendAction();
  }
});

Now, when specifying your form, you can tell your component what type of button it should be.

现在,在指定表单时,您可以告诉组件它应该是什么类型的按钮。

inside form: {{my-button action="clicked" type="button"}}

http://jsbin.com/zutacipido/2/edit

http://jsbin.com/zutacipido/2/edit