I am currently working on creating a single page application (SPA) using Mithril.js. While I have come across some helpful tutorials like the one here and on the official Mithril homepage, I am struggling to combine the concepts from both sources effectively.
Below is a modified example inspired by Dave's guide...
function btn(name, route){
var click = function(){ m.route(route); };
return m( "button", {onclick: click}, name );
}
function Page(content){
this.view = function(){
return [
m("page",
m("span", Menu.menu())
)
, m("div", content)
];
}
}
var Menu = {
menu: function(){
return [
btn("Home", "/home")
, btn("About", "/about")
];
}
};
var page_Home = new Page("The home of the Hobbits. Full of forests and marshes.");
var page_About = new Page(["The blighted home of Sauron. Scenic points of interest include:"]);
m.route(document.body, "/home", {
"/home": page_Home,
"/about": page_About
});
Here is my JSON file:
[
{
"id":1,
"title": "Home",
"url": "/home",
"content":"This is home page"
},{
"id":2,
"title": "About",
"url": "/about",
"content":"This is about page"
},{
"id":3,
"title": "Gallery",
"url": "/gallery",
"content":"This is gallery page"
}
]
My attempt at combining the JSON data with the previous example:
//model
var PageSource = {
list: function() {
return m.request({method: "GET", url: "pages.json"});
}
};
var pages = PageSource.list();
var App = {
//controller
controller: function() {
return {
menu: pages
, rotate: function() { pages().push(pages().shift()); }
, id: m.route.param(pages.url)
}
},
//view
view: function(ctrl) {
return [
m("header"
, m("h1", "Page Title")
, m("span",
ctrl.menu().map(function(item) {
var click = function(){
console.log (item.url);
m.route(item.url);
};
return [
m("button", {onclick: click}, item.title)
];
})
)
, m("hr")
)
, m("button", {onclick: ctrl.rotate}, "Rotate links" )
, m("p", ctrl.content ) //CONTENT
];
}
};
//initialize
m.route(document.body, "/home", {
"/:id": App
});
And now for my questions: - "How can I fetch data from a JSON file and display it in a div based on the selected button (routing)?" - "When using m.route, my entire view refreshes, but I only want to reload the changed div. How can I achieve this?" I would appreciate any help, as I am really enjoying working with Mithril.js so far.