Skip to content

Instantly share code, notes, and snippets.

@nummi
Last active March 24, 2016 00:47
Show Gist options
  • Save nummi/9979494 to your computer and use it in GitHub Desktop.
Save nummi/9979494 to your computer and use it in GitHub Desktop.
Ember Content Editable Component w/ Placeholder
# 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()
@anilmaurya
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment