0

Unable to attach two way data binding to a <div contenteditable> tag. Here is the demo

html:

<body>
    <div contenteditable style="height:40px;min-width:40px">{{content}}</div>
</body>

js:

if (Meteor.isClient) {
    Session.setDefault('content', 'Try to edit me')

    Template.body.helpers({
        content: function () {
            return Session.get('content')
        }
    })

    Template.body.events({
        'keydown div': function (e) {
            setTimeout(function(){ Session.set('content', $(e.target).text()) })
        }
    })
}

There is also an open issue for this at github.

brg
  • 113
  • 8

2 Answers2

0

you can use the 'input' event

meteorpad fork of your example : http://meteorpad.com/pad/x3JQpGiqpE2FrTfLK/content%20editable

related question : contenteditable change events

 Template.body.events({
    'input div': function (e) {
      Session.set('content', $(e.target).text());
    }
  });

However, there is a problem with binding editable elements in general, you'll notice each input event results in setting the text twice.

You can get around this by clearing out the editable text after each edit :

Template.body.events({
    'input div': function (e) {
      Session.set('content', $(e.target).text());
      $(e.target).text('');
    }
  });

But now you have another problem, the cursor jumps to the beginning.

In order to deal with these dilemmas, I use this logic :

"Did the user make this most recent edit to the data model?"

  • update the data model with the user's most recent text. Don't update the text editor. be optimistic.

  • if the update failed, set the text editor to the data model ( revert their edit, display some error )

"Did something besides the user change the data model for the text ? "

  • update the text editor to show the most recent text
Community
  • 1
  • 1
looshi
  • 1,226
  • 2
  • 9
  • 23
  • 1
    then also you probably want to use underscore's debounce for the input event for some better performance. – looshi Mar 08 '15 at 23:21
0

Or just use https://github.com/gwendall/meteor-bindings. It makes use of reactive variables to bind any DOM element to inputs.

Disclaimer: I built it.

gwendall
  • 920
  • 15
  • 22
  • To data-bind a particular property in a collection? – brg Mar 15 '15 at 06:33
  • Seems like the code is not maintained anymore. Would also be interested getting it working with mongo connections. Any alternatives? – Lucbug Dec 20 '17 at 08:12