【问题标题】:Do not type newline when enter pressed in textarea in EmberJS在 EmberJS 的 textarea 中按下输入时不要输入换行符
【发布时间】:2014-07-24 15:57:21
【问题描述】:

我需要在按下 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()

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.

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

【问题讨论】:

  • TextArea 设计为多行。如果您只想支持单行,为什么不直接使用<input type="text" /> 我们可以了解一下您为什么要这样做,这是非常规的吗?
  • @Scott 问题是字符串可能很长,我需要能够显示 TextArea 的所有内容,使其更高,这是 TextField 无法做到的。或者可能?
  • 有什么办法可以在acceptChanges中使用preventDefault

标签: javascript jquery ember.js


【解决方案1】:

我最近也必须这样做,结果证明它相当简单。这是一个非常简单的组件:

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'}} 添加到您的车把某处。当用户按下回车键时,会触发动作 'foo'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多