I have a form inside a View. How and where can I handle the form submit event? Also where can I write the code for handling events on elements present in this form. I tried handling it at:
//Instantiating a view with a template name signup
var signup = Ember.View.create({
templateName: "signup",
name: 'Sign Up',
click: function()
{
alert('click triggered from signup template');
},
submit: function()
{
alert('submit triggered');
},
signup: function()
{
alert('signup triggered');
}
});
<script type="text/x-handlebars" data-template-name="signup">
<form class="form-horizontal" {{action "signup" on="submit"}}>
<br/>
<div align="center" >
<table class="table-hover>
<tr>
<td>
<label>First Name</label>
</td>
<td>
{{input value=firstName class="controls" type="text"}}
</td>
</tr>
<tr>
<td>
<label>Last Name</label>
</td>
<td>
{{input value=lastName class="controls" type="text"}}
</td>
</tr>
<button class="btn btn-primary " type="submit" >Register</button>
</div>
</form>
</script>
When I click anywhere on the button, only click event is triggered. How do I get access to the submit event?
My answer includes, two solutions. The first being a method using views correctly. The second solution uses an Ember Component, which I think is closer to what you were looking to do.
Ember View Method:
I have created a working demo here, for you to look at.
The are a few things you need to do:
Your template code:
You need to be careful that you create clean and valid code. You have not closed the class name on your
<table>
tag nor have you included the closing</table>
tag. This is the cleaned up template:Using your view:
You cannot add actions to a view like that. Actions of the view must be handled either on the
Route
or theController
. See here for examples on how to use actions with a view.Essentially, your action handler would be trying to pass the action to the controller, or route that was including your view. Notice in my demo, that the
IndexRoute
has the model, and the action to take, and that the index template referenced the view:Ember Component Method:
If you want to keep the action inside your view, then you need to use a component. See this demo, for use as a component.
It's usage is slightly different, but now the action is self contained, and does not need to be included in the
Route
orController
which is perhaps more what you were looking for.To use it you can do:
Your model data is now accessible in the component by doing
data.firstName
anddata.lastName
, so the template is slightly modified too. You can see this in the HTML section of the JSBin demo I included.I hope this helps.