如果我在表单中放置一个按钮并单击它,则只会触发按钮单击事件。
但是,如果我构建了一个按钮组件" my-button",请将该按钮替换为" my-button"然后再次单击它,它会触发按钮单击事件,但也会提交表单。
它应该表现得那样吗?如何让我的组件不提交表单?
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>
&#13;
我还创建了一个JS Bin。任何点击事件都会“点击”到控制台,表单提交会将“提交”记录到浏览器控制台中。
答案 0 :(得分:1)
问题在于您没有指定按钮的类型,默认情况下,按钮类型是&#34;提交&#34;然后提交您的操作。您可以通过在组件中指定按钮类型来更改此项。
App.MyButtonComponent = Ember.Component.extend({
tagName: "button",
attributeBindings: ['type'],
click: function(){
this.sendAction();
}
});
现在,在指定表单时,您可以告诉组件它应该是什么类型的按钮。
inside form: {{my-button action="clicked" type="button"}}