简体   繁体   English

流星-有没有办法让div contenteditable两种方式的数据绑定起作用?

[英]Meteor - Is there a way to get div contenteditable two way data binding to work?

Unable to attach two way data binding to a <div contenteditable> tag. 无法将两种方式的数据绑定附加到<div contenteditable>标记。 Here is the demo 这是演示

html: 的HTML:

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

js: 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. github上还有一个未解决的问题

you can use the 'input' event 您可以使用“输入”事件

meteorpad fork of your example : http://meteorpad.com/pad/x3JQpGiqpE2FrTfLK/content%20editable 您的示例的meteorpad分支: 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 更新文本编辑器以显示最新文本

Or just use https://github.com/gwendall/meteor-bindings . 或者只是使用https://github.com/gwendall/meteor-bindings It makes use of reactive variables to bind any DOM element to inputs. 它利用反应变量将任何DOM元素绑定到输入。

Disclaimer: I built it. 免责声明:我构建了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM