Ember.js - Replacement cases for Ember.Button
HTML
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-0.9.4.js"></script>
<h1>Replacement cases for Ember.Button</h1>
<h2>Case 1: button for submitting a form</h2>
<script type="text/x-handlebars">
{{#view App.Form controllerBinding="App.peopleController"}}
{{view Ember.TextField viewName="textField"}}
<button type="submit">Add Person</button>
{{/view}}
<ul>
{{#each App.peopleController}}
<li>{{name}}</li>
{{/each}}
</ul>
</script>
<h2>Case 2: performing an action as a button</h2>
<script type="text/x-handlebars">
{{#view App.NotAForm}}
<button {{ action "hello" }}>Say Hi</button>
{{/view}}
</script>
<h2>Case 3: performing an action as a link</h2>
<script type="text/x-handlebars">
{{#view App.NotAForm}}
<a href="#" {{ action "hello" }}>Say Hi</a>
{{/view}}
</script>
CSS
h1 { font-size: 130%; margin: 10px 0 }
h2 { font-size: 115%; font-weight: bold; margin: 10px 0 }
JavaScript
window.App = Ember.Application.create();
App.peopleController = Em.ArrayController.create({
content: [{name: "Joe"}, {name: "Jane"}],
addPerson: function(name) {
this.unshiftObject(App.Person.create({name: name}));
}
});
App.Person = Em.Object.extend({
name: null
});
App.Form = Em.View.extend({
tagName: 'form',
controller: null,
textField: null,
submit: function(event) {
event.preventDefault();
this.get('controller').addPerson(this.getPath('textField.value'));
this.setPath('textField.value', null);
}
});
App.NotAForm = Em.View.extend({
hello: function(event) {
// should preventDefault() be the default for {{action}} ?
// it's not always strictly necessary, but is probably best
// in most cases
event.preventDefault();
alert("Hi");
}
});