Insert Ember component at cursor in contentEditable element

江枫思渺然 提交于 2019-12-02 13:48:09

问题


I have a contentEditable div where I want to allow users to type text, as well as insert input elements such as text boxes and dropdowns. The elements will be inserted where the cursor currently is, by allowing the user to click a button outside the editable div.

I got it working pretty well following this general example:

http://jsfiddle.net/jwvha/1/

which basically does a

document.selection.createRange().pasteHTML(html);

The problem is that it expects HTML to be passed into the function which inserts the element at cursor. For more complex things, I'd like to be able to insert Ember components with full html/js logic available, instead of trying to put all html/js into a string.

Is there a way to programmatically create a component AND insert it into a contentEditable element at cursor, while maintaining its functionality, such as actions, etc.

I'm on Ember 2.5 currently.


回答1:


I think you could use a ember-cli plugin called ember-wormhole. What this component do is basically move the dom of you ember component to an html element that contains an id attribute.

e.g.

document.selection.createRange().pasteHTML('<div id="my-component-id"></div>');

use my-component-id to ember-wormhole destinantion attribute:

{{#ember-wormhole to="my-component-id"}}
    {{my-component...}}
{{/ember-wormhole}}

Regarding that, you could do something like:

click() {
    let componentId = 'my-component-id';

    document.selection.createRange().pasteHTML(`<div id="${componentId}"></div>`);
    this.get('components').pushObject(componentId); // components being an array
}

in your handlebars template:

{{#each components as |componentId|}}
    {{#ember-wormhole to=componentId}}
        {{my-component...}}
    {{/ember-wormhole}}
{{/each}}


来源:https://stackoverflow.com/questions/37714810/insert-ember-component-at-cursor-in-contenteditable-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!