Search code examples
ractivejs

Get data from the parent scope


Im trying to implement a single-page app with Ractive using components, and I need to have some page-wide options. I did like this:

...
data: {
    options: {
        someOption: true
    },
...

Everything was fine while I used it like {{#if options.someOption}}, but then I faced a problem - rective.get('options.someOption') returns undefined (both with ractive.get('options')). Observing dont work as well. Is there any way to make my code understand me?

UPD. Accidentally solved problem with a portion of magic - get() starts working when I place {{options.someOption}} on template.


Solution

  • Ractive programmatic data access within an instance (includes components) can currently only "see" data that is:

    1. Defined as data
    2. Specified explicitly as a component parameter
    3. Used as a reference in the template

    For #1, you can include the options as default data and it will be available to all instances:

    Ractive.default.data = {
        options: {...}
    }
    

    Any new Ractive instance, including components, will have an options data property.

    For #2, even if you have deeply nested components, you can have the parent of the component that needs the data include it as a parameter:

    // Component somewhere in the "app" hierarchy.
    // By referencing {{options}} in its template, it will find that data
    // make it explicit on the widget component, which can then use it
    // programmatically
    
    <widget options='{{options}}'/>
    

    For #3, you can include a "dummy" reference in the component template:

    // by using it in the template, it is now available for programatic access
    {{#with options}}{{/with}}
    

    Of course then there's #4, enhancing Ractive to allow same lookup in code as template