Search code examples
javascriptnativescriptuibuilder

NativeScript UI-Builder


I try to build a simple form-like UI where I want to dynamically add rows of multiple TextFields. I built a custom component with XML and JS, because there is some interaction in these TextFields (start, end, duration).

I am a starter in NativeScript, but I got my databinding and event-structure going. I was able to add my custom component via ui/builder. Where I am totally stuck is getting "options/arguments" to this component-instance. What I try to accomplish is: Adding my custom component and giving it some data which should be filled into the components Obsverable. At a later (save) action I want to be able to retrieve these data from my "main" view.

My structure is something like this:

main.js

exports.loaded = function(args) {
    var page = args.object;
    page.bindingContext = model;

    var outerContainer = page.getViewById('outerContainer');

    var vma = builder.load({
        path: 'widgets/durationRow',
        name: 'durationRow'
    });

    outerContainer.addChild(vma);
};

custom component "durationRow.js"

var componentModel = new Observable({
    label:      "",
    start:      "",
    end:        "",
    duration:   ""
});

exports.onLoad = function(args){
    var container = args.object;
    container.bindContext = componentModel;
};

I tried to export the componentModel via exports.componentModel and address vma.componentModel from main. But vma is a view not the "JS-module". I am really stuck and didn't find any example doing something like my scenario.

Can anyone point me in the right direction how I can do this stuff the right (or any) way?

thanks!


Solution

  • So the answer to that problem is quite simple: read the documentation :)

    There is an option attributes which can be used exactly for that. I ended up with this:

    var row = builder.load({
        path: 'widgets/durationRow',
        name: 'durationRow',
        attributes: {
            bindingContext: bindingModel
        }
    });
    container.addChild( row );
    

    And in the loaded widget I'll get my "inserted" model as bindingContext:

    exports.onLoad = function(args){
        page = args.object;
        var model = page.bindingContext;
    };
    

    I hope this helps!