7

I am trying to create a custom component in knockout.js.

HTML

<demo-widget>TEXT NEEDED</demo-widget>

Javascript

ko.components.register('demo-widget', {
    template: '<div>New Text</div>'
});

ko.applyBindings();

The component loads fine and everything, but what I now want to do is to be able to get any content that was inside the original custom component tag(example the "TEXT NEEDED" text).

Any idea how I can do this? Hope I explained it clearly enough.

Here is a fiddle: http://jsfiddle.net/WhesleyBarnard/f7bmynp5/5/

Whesley Barnard
  • 309
  • 1
  • 10

2 Answers2

4

This is possible now (as of Knockout 3.3), see the KnockoutJS documentation here: Passing markup into components.

I won't copy the whole text here, but the gist is:

By default, the DOM nodes inside [your component] will be stripped out (without being bound to any viewmodel) and replaced by the component’s output. However, those DOM nodes aren’t lost: they are remembered, and are supplied to the component in two ways:

  • As an array, $componentTemplateNodes, available to any binding expression in the component’s template (i.e., as a binding context property). Usually this is the most convenient way to use the supplied markup. See the example below.
  • As an array, componentInfo.templateNodes, passed to its createViewModel function

The component can then choose to use the supplied DOM nodes as part of its output however it wishes, such as by using template: { nodes: $componentTemplateNodes } on any element in the component’s template.

Related SO question: Knockout 3.2: can components / custom elements contain child content?

Community
  • 1
  • 1
w5l
  • 5,341
  • 1
  • 25
  • 43
1

Why not use the params attribute to save the initial text:

html:

<demo-widget params="initialValue: 'text i need to get...'"></demo-widget>

js:

ko.components.register('demo-widget', {
    template: "<div data-bind=\"text: 'content in my component. previous was: '
                                      + initialValue \">
               </div>"
});

ko.applyBindings();
manji
  • 47,442
  • 5
  • 96
  • 103
  • I want it to be able to handle large amounts of html inside the tags. – Whesley Barnard Oct 09 '14 at 15:38
  • @WhesleyBarnard, the moment knockout applies bindings, the content is erased. You should save that content somewhere else, another element (maybe hidden) not processed by ko. If this is not suitable, then what are you trying to achieve exactly? – manji Oct 09 '14 at 15:43
  • Hi. I am just trying some proof of concepts. Like let say I wanted to created my own little wiziwig editor. It would then take all the content inside the tag and you would be able to manipulate it. If I use the params I will definitely get it to work, just thought it would be cool if we were able to grab the content inside the tags as well. – Whesley Barnard Oct 10 '14 at 06:11