简体   繁体   中英

mithril hello world MVC example not working

I am having trouble getting the Mithril hello world MVC example working.

Here is my code, as copied from the Mitrhil homepage . Note the only change I made was to swap the m.request({method: "GET", url: "pages.json"}); method call to a manually generated pages object.

//namespace
var app = {};

//model
app.PageList = function() {
    var pages = [];
    pages.push({title: 'page 1', url: '/page1.html'});
    pages.push({title: 'page 2', url: '/page2.html'});
    return pages;
};

//controller
app.controller = function() {
    var pages = app.PageList();
    return {
        pages: pages,
        rotate: function() {
            pages().push(pages().shift());
        }
    }
};

//view
app.view = function(ctrl) {
    return [
        ctrl.pages().map(function(page) {
            return m("a", {href: page.url}, page.title);
        }),
        m("button", {onclick: ctrl.rotate}, "Rotate links")
    ];
};

//initialize
m.module(document.getElementById("example"), app);

As you can see, my example above in jsFiddle doesn't work, but another Mitrhil example, the todo app jsFiddle works fine.

I think it would make sense for the basic MVC Mitrhil example to work simply like the Todo app does, and possibly link to a jsFiddle or CodePen example for users to fork, similar to in React.

There were some calls to pages which should have been variable references instead, since it's an Array. Here's the fix: http://jsfiddle.net/jug68s27/4/

ctrl.pages() -> ctrl.pages

pages().push(pages().shift()) -> pages.push(pages.shift())

In this example the value not redraw because you didn't use m.prop , if you want that the value change you cas use var pages = m.prop(''); Now you can use pages().push or ctrl.pages().map because m.prop is a function!!!! Remember this it's very important, you will use it a lot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM