Retrieving the contents of custom knockout.js components

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 everything and everything, but now I want to get any content that was inside the original tag of the component (for example, the text "REQUIRED TEXT").

Any idea how I can do this? I hope I explained this quite clearly.

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

+6
source share
2 answers

Why not use the params attribute to save the source 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(); 
+1
source

This is now possible (starting with Knockout 3.3), see the documentation for KnockoutJS: Passing markup to components .

I will not copy all the text here, but the gist is this:

By default, the DOM nodes within [your component] will be deleted (without being tied to any viewing model) and replaced with output components. However, those DOM nodes arent lost: they are remembered and passed to the component in two ways:

  • Like an array of $componentTemplateNodes , available for any binding expression in a component template (i.e., as a property of a binding context). This is usually the most convenient way to use the supplied markup. See the example below.
  • The createViewModel function is passed as the componentInfo.templateNodes array

Then the component can then use the supplied DOM nodes as part of its output, but it wants, for example, using template: { nodes: $componentTemplateNodes } for any element in the component template.

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

+3
source

Source: https://habr.com/ru/post/976498/


All Articles