Reputation: 777
I need to submit changes when the Enter key is pressed, rather than typing a newline symbol. I'm using Ember.js and slightly customized TextArea helper.
Here is what I have in my template
{{edit-item placeholder="Weight" value=weight insert-newline="acceptChanges" focus-out="acceptChanges"}}
in my helper
App.EditItemView = Em.TextArea.extend
didInsertElement: ->
this.$().focus()
this.$().blur()
focusIn: ->
$this = this.$()
$this.get(0).select()
# fix webkit select problems
mouseUpHandler = ->
$this.off("mouseup", mouseUpHandler)
return false
$this.mouseup(mouseUpHandler)
attributeBindings: ['style', 'placeholder']
Em.Handlebars.helper 'edit-item', App.EditItemView
and in my acceptChagnges
action
# In controller action hook up
acceptChanges: ->
$(document.activeElement).blur()
@get('model').save()
The real problem is that when text selected and user types enter key to accept, it also types a newline which replaces all content in textarea, hence the only newline gets accepted.
How to prevent typing new line, but fire an event to accept changes?
Upvotes: 3
Views: 1711
Reputation: 12172
I had to do this as well recently, and it turns out it's fairly simple. Here is a pretty bare component which does this:
App.NoteBoxComponent = Ember.TextArea.extend({
keyDown: function (event) {
if (event.which === 13 && ! event.shiftKey) {
// Don't insert newlines when submitting with enter
event.preventDefault();
}
},
// This next bit lets you add newlines with shift+enter without submitting
insertNewline: function (event) {
if (! event.shiftKey) {
// Do not trigger the "submit on enter" action if the user presses
// SHIFT+ENTER, because that should just insert a new line
this._super(event);
}
}
});
To use this, just add {{note-box action='foo'}}
to your handlebars somewhere. The action 'foo' will be triggered when the user hits enter.
Upvotes: 5