Last active
March 24, 2016 00:47
-
-
Save nummi/9979494 to your computer and use it in GitHub Desktop.
Ember Content Editable Component w/ Placeholder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# modified from: https://github.com/KasperTidemann/ember-contenteditable-view | |
App.ContentEditableComponent = Em.Component.extend | |
attributeBindings: ['contenteditable', 'placeholder'] | |
editable: true | |
placeholder: null | |
plaintext: false | |
preventEnterKey: false | |
_userIsTyping: false | |
setup: (-> | |
@setHTMLFromValue() | |
@setPlaceholder() if @elementIsEmpty() and @get('placeholder') | |
).on('didInsertElement') | |
# Properties: | |
contenteditable: (-> | |
editable = @get('editable') | |
(if editable then 'true' else `undefined`) | |
).property('editable') | |
# Observers: | |
valueDidChange: (-> | |
@setHTMLFromValue() if @get('value') and not @get('_userIsTyping') | |
).observes('value') | |
# DOM Events: | |
keyDown: (event) -> | |
@set('_userIsTyping', true) | |
@supressEnterKeyEvent(event) if @get('preventEnterKey') | |
@removePlaceholder() if @elementHasPlaceholder() | |
keyUp: (event) -> | |
if @elementIsEmpty() || @elementHasPlaceholder() | |
@set('value', '') | |
@setPlaceholder() | |
return | |
@setValueFromHTML() | |
focusOut: -> | |
@set '_userIsTyping', false | |
@setPlaceholder() if @elementIsEmpty() | |
elementIsEmpty: -> | |
Em.isEmpty(@.$().text()) | |
elementHasPlaceholder: -> | |
@.$().text() == @get('placeholder') | |
setPlaceholder: -> | |
@.$().text(@get('placeholder')).addClass('placeholder') | |
removePlaceholder: -> | |
@.$().text('').removeClass('placeholder') | |
setHTMLFromValue: -> | |
@.$().html(@get('value')) | |
setValueFromHTML: -> | |
if @get('plaintext') | |
@set 'value', @.$().text() | |
else | |
@set 'value', @.$().html() | |
supressEnterKeyEvent: (e) -> | |
if e.keyCode == 13 || e.which == 13 | |
e.preventDefault() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks