javascript - 在 EmberJS 的文本区域中按下输入时不要输入换行符

标签 javascript jquery ember.js

我需要在按下 Enter 键时提交更改,而不是键入换行符。我正在使用 Ember.js 和稍微自定义的 TextArea 助手。

这是我的模板中的内容

{{edit-item placeholder="Weight" value=weight insert-newline="acceptChanges" focus-out="acceptChanges"}}

在我的助手中

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

在我的acceptChagnges 操作中

# In controller action hook up 
acceptChanges: ->
  $(document.activeElement).blur()
  @get('model').save()

真正的问题是,当文本被选中并且用户键入接受键时,它还会键入一个换行符来替换 textarea 中的所有内容,因此唯一的换行符被接受。

如何防止输入新行,但触发事件以接受更改?

最佳答案

我最近也必须这样做,事实证明这很简单。这是一个非常简单的组件,可以执行此操作:

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);
        }
    }

});

要使用它,只需将 {{note-box action='foo'}} 添加到您的 Handlebars 某处。用户按下回车键时将触发操作“foo”。

关于javascript - 在 EmberJS 的文本区域中按下输入时不要输入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20836402/

相关文章:

javascript - 数据表导出至excel

javascript - 在 JavaScript 中为移动浏览器附加链接

javascript - Ember.js 中的 SortBy 不适用于新创建的项目

javascript - setInterval 只是不会随着clearInterval 停止

JavaScript RegEx 用于替换字符串中以 # 开头的单词

javascript - AngularJS ng-switch-when 表达式

jquery - CSS/jQuery 防止在某些 Div 上滚动

javascript - 在内容更新时保留复选框值

javascript - ember 核心表单组件中的 ARIA 属性

javascript - 如何在 Ember js 中获取 currentRouteName 的动态部分