Search code examples
knockout.jsknockout-components

Getting knockout.js custom component content


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/


Solution

  • 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();