Stefan Hermanek
Stefan Hermanek

Reputation: 103

Nesting components with mithril.js

I'm trying to put together some nested components to assemble a larger page. The use of the interim steps to create the view seems like an overkill, but this is only one part of many more components that will be put together. Beside that it gives a good overview what is happening. But I don't get it right without errors.

Here is a code example

var MyApp = {
    controller: function() {
        return {loaded: true}
    },
    view: function(ctrl) {
        return //[  // remove comment for var1
            m("button[type=button]", {onclick: function() {ctrl.loaded = false}})
            , ctrl.loaded ? MyComponent : ""
            //]    // remove comment for var1
    }
}

var MyComponent = {
    controller: function() {
        return {
            onunload: function() {
                console.log("unloaded!")
            }
        }
    },
    view: function() {
        return m("h1", "My component")
    }
}

var MainCompCtrl = function() {
    var ctrl = this
    ctrl.name = "test";
}


var MainCompView = function(ctrl, args) {

    var partComp = m.component(MyApp);
    var part_myComp = m(".row", [ m(".col-md-2", [partComp] ) ]); 

    var part5 = m("[id='2']", {class : 'commandContainer'}, "2", [part_myComp]); 
    return part5;
};

// var1 working
//m.mount(document.body, MyApp)

// var2 not working
m.mount(document.body, m.component(
        {controller : MainCompCtrl, view : MainCompView}));

Here is a fiddle with the not working variant var2: http://jsfiddle.net/1f7uauav/

The error message is:

TypeError: data is undefined
if (data.subtree === "retain") return cached;

To see the working var1 please remove comment as indicated in the fiddle (line 6, 9, 42) and comment lines 45 and 46. Now you can see the desired result, but this way I can't use MyApp inside other components.

So, what's wrong with this code in var2?

Thanks, Stefan

Upvotes: 1

Views: 1049

Answers (1)

Stefan Hermanek
Stefan Hermanek

Reputation: 103

Problem solved, in JavaScript never let a return be followed by a line break like this:

return //[  // remove comment for var1
    m("button[type=button]", {onclick: function() {ctrl.loaded = false}})
    , ctrl.loaded ? MyComponent : ""
    //]    // remove comment for var1

Sorry for this, Stefan

Upvotes: 1

Related Questions