### Clone and run mithril-esbuild-starter Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Steps to clone a Mithril.js esbuild starter template, navigate into it, install dependencies, and start the development server. ```bash npx degit kevinfiol/mithril-esbuild-starter hello-world ``` ```bash cd ./hello-world/ ``` ```bash npm install ``` ```bash npm run dev ``` -------------------------------- ### Render 'Hello World' Live Example Source: https://github.com/mithriljs/docs/blob/main/docs/index.md A live example demonstrating rendering 'Hello World' text using Mithril.js. This showcases the basic rendering capability. ```javascript var root = document.body m.render(root, "Hello World") ``` -------------------------------- ### Run the esbuild start script Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Executes the 'start' script defined in package.json, which bundles the application using esbuild and watches for file changes. ```bash $ npm run start ``` -------------------------------- ### Install Babel CLI and Preset Env Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Install Babel CLI and preset-env as development dependencies to enable transpilation. ```bash npm install @babel/cli @babel/preset-env --save-dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/mithriljs/docs/blob/main/CONTRIBUTING.md Run this command before using any of the npm scripts to install necessary project dependencies. ```bash npm install ``` -------------------------------- ### Live Example: Routing and Components Source: https://github.com/mithriljs/docs/blob/main/docs/index.md A comprehensive example demonstrating Mithril.js routing with multiple components and event handling. ```javascript var root = document.body var count = 0 var Hello = { view: function() { return m("main", [ m("h1", { class: "title" }, "My first app"), m("button", { onclick: function() {count++} }, count + " clicks"), ]) } } var Splash = { view: function() { return m("a", { href: "#!/hello" }, "Enter!") } } m.route(root, "/splash", { "/splash": Splash, "/hello": Hello, }) ``` -------------------------------- ### Basic Code Splitting with onmatch Source: https://github.com/mithriljs/docs/blob/main/docs/route.md Demonstrates how to implement code splitting by returning a promise from the onmatch hook. This example shows a basic setup for lazy loading a module. ```javascript // Home.js module.export = { view: function() { return [ m(Menu), m("h1", "Home") ] } } ``` ```javascript // index.js function load(file) { return m.request({ method: "GET", url: file, extract: function(xhr) { return new Function("var module = {}" + xhr.responseText + ";return module.exports;") } }) } m.route(document.body, "/", { "/": { onmatch: function() { return load("Home.js") }, }, }) ``` -------------------------------- ### Configure npm start script for esbuild Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Adds a 'start' script to package.json to bundle and watch for changes using esbuild. Includes options for JSX. ```json { "...": "...", "scripts": { "start": "esbuild index.js --bundle --outfile=bin/main.js --watch" } } ``` ```json { "...": "...", "scripts": { "start": "esbuild index.js --bundle --outfile=bin/main.js --jsx-factory=m --jsx-fragment='\"[\"' --watch" } } ``` -------------------------------- ### Run Development Build with npm Start Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Use 'npm start' to execute the defined development build script, simplifying the command to run Webpack. ```bash npm start ``` -------------------------------- ### Install Mithril.js via npm Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Install the Mithril.js package using npm for use in your project. Also shows how to install TypeScript definitions. ```bash $ npm install mithril ``` ```bash $ npm install @types/mithril --save-dev ``` -------------------------------- ### Live Example: Mithril.js App with XHR Source: https://github.com/mithriljs/docs/blob/main/docs/index.md A complete, runnable example demonstrating a Mithril.js application that uses `m.request` to update a counter on a server and display the result. It includes component definition, XHR logic, and mounting the application. ```javascript var root = document.body var count = 0 var increment = function() { m.request({ method: "PUT", url: "//mithril-rem.fly.dev/api/tutorial/1", body: {count: count + 1}, withCredentials: true, }) .then(function(data) { count = parseInt(data.count) }) } var Hello = { view: function() { return m("main", [ m("h1", { class: "title" }, "My first app"), m("button", { onclick: increment }, count + " clicks"), ]) } } m.mount(root, Hello) ``` -------------------------------- ### Include Mithril.js from CDN Source: https://github.com/mithriljs/docs/blob/main/docs/index.md Include Mithril.js using a CDN link in your HTML file to get started. This setup is used for following along with tutorials. ```html ``` -------------------------------- ### Run All Tests Source: https://github.com/mithriljs/docs/blob/main/docs/contributing.md Execute all tests in the project after installing dependencies. ```bash npm test ``` -------------------------------- ### Live Example: Interactive Component Source: https://github.com/mithriljs/docs/blob/main/docs/index.md A complete example of an interactive Mithril component with event handling and auto-redrawing. ```javascript var root = document.body var count = 0 // added a variable var Hello = { view: function() { return m("main", [ m("h1", { class: "title" }, "My first app"), m("button", { onclick: function() {count++} }, count + " clicks") ]) } } m.mount(root, Hello) ``` -------------------------------- ### Install Webpack and Babel Dependencies Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Install necessary packages for Webpack and Babel, including loaders and presets. Use --save-dev for development dependencies. ```bash npm install webpack webpack-cli @babel/core babel-loader @babel/preset-env --save-dev ``` -------------------------------- ### Watch and Serve Documentation Locally Source: https://github.com/mithriljs/docs/blob/main/CONTRIBUTING.md Builds the docs on change, lints them, and starts a local server at http://localhost:8080/. This is the most frequently used command for local development. ```bash npm run watch ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/mithriljs/docs/blob/main/docs/testing.md Install ospec, mithril-query, and jsdom as development dependencies for testing Mithril.js applications. ```bash npm install --save-dev ospec mithril-query jsdom ``` -------------------------------- ### Basic JSX Component Example Source: https://github.com/mithriljs/docs/blob/main/docs/jsx.md Illustrates how to write a Mithril component using JSX syntax, comparing it to the hyperscript equivalent. ```jsx function MyComponent() { return { view: () => m("main", [m("h1", "Hello world")]), }; } // can be written as: function MyComponent() { return { view: () => (

Hello world

), }; } ``` -------------------------------- ### Install Mithril and esbuild Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Installs Mithril.js and esbuild as development dependencies. esbuild is used for bundling the JavaScript code. ```bash $ npm install mithril $ npm install esbuild --save-dev ``` -------------------------------- ### Basic GET Request with m.request Source: https://github.com/mithriljs/docs/blob/main/docs/request.md Make a simple GET request to a specified URL. The response is logged to the console upon successful completion. Assumes JSON response format. ```javascript m.request({ method: "GET", url: "/api/v1/users", }) .then(function(users) { console.log(users) }) ``` -------------------------------- ### JSX Component Example Source: https://github.com/mithriljs/docs/blob/main/docs/jsx.md Demonstrates an equivalent Mithril.js component using JSX syntax for its view. This approach is more HTML-like but requires a build step. ```jsx function SummaryView() { let tag, posts; function init({ attrs }) { Model.sendView(attrs.tag != null); if (attrs.tag != null) { tag = attrs.tag.toLowerCase(); posts = Model.getTag(tag); } else { tag = undefined; posts = Model.posts; } } function feed(type, href) { return (
{type}
); } return { oninit: init, // To ensure the tag gets properly diffed on route change. onbeforeupdate: init, view: () => (

My ramblings about everything

{feed("Atom", "blog.atom.xml")} {feed("RSS", "blog.rss.xml")}
tag != null ? ( ) : (
Posts, sorted by most recent
)
{posts.map((post) => (
{post.title}
{post.preview}...
))}
) }; } ``` -------------------------------- ### Basic Route Setup Source: https://github.com/mithriljs/docs/blob/main/docs/route.md Sets up the primary routing for an application. You can only have one `m.route` call per application. The `root` argument is the DOM element that will contain the routed component. ```javascript var Home = { view: function() { return "Welcome" } } m.route(document.body, "/home", { "/home": Home, // defines `https://localhost/#!/home` }) ``` -------------------------------- ### Hyperscript Component Example Source: https://github.com/mithriljs/docs/blob/main/docs/jsx.md Illustrates a Mithril.js component using hyperscript syntax for defining its view. This approach is concise and can be used without a build step. ```javascript function SummaryView() { let tag, posts; function init({ attrs }) { Model.sendView(attrs.tag != null); if (attrs.tag != null) { tag = attrs.tag.toLowerCase(); posts = Model.getTag(tag); } else { tag = undefined; posts = Model.posts; } } function feed(type, href) { return m(".feed", [ type, m("a", { href }, m("img.feed-icon[src=./feed-icon-16.gif]")), ]); } return { oninit: init, // To ensure the tag gets properly diffed on route change. onbeforeupdate: init, view: () => m(".blog-summary", [ m("p", "My ramblings about everything"), m(".feeds", [ feed("Atom", "blog.atom.xml"), feed("RSS", "blog.rss.xml"), ]), tag != null ? m(TagHeader, { len: posts.length, tag }) : m(".summary-header", [ m( ".summary-title", "Posts, sorted by most recent." ), m(TagSearch), ]), m( ".blog-list", posts.map((post) => m( m.route.Link, { class: "blog-entry", href: `/posts/${post.url}`, }, [ m( ".post-date", post.date.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", })), m(".post-stub", [ m(".post-title", post.title), m(".post-preview", post.preview, "..."), ]), m(TagList, { post, tag }), ] ) ) ), ]); }; } ``` -------------------------------- ### Mithril.js Test Setup File Source: https://github.com/mithriljs/docs/blob/main/docs/testing.md Set up the global environment for Mithril.js testing using JSDOM, including window, document, and requestAnimationFrame. Ensure JSDOM is closed after tests. ```javascript var o = require("ospec") var jsdom = require("jsdom") var dom = new jsdom.JSDOM("", { // So we can get `requestAnimationFrame` pretendToBeVisual: true, }) // Fill in the globals Mithril.js needs to operate. Also, the first two are often // useful to have just in tests. global.window = dom.window global.document = dom.window.document global.requestAnimationFrame = dom.window.requestAnimationFrame // Require Mithril.js to make sure it loads properly. require("mithril") // And now, make sure JSDOM ends when the tests end. o.after(function() { dom.window.close() }) ``` -------------------------------- ### Implement Login Wall for Protected Routes Source: https://github.com/mithriljs/docs/blob/main/docs/route.md This example shows how to create a login wall for a protected route. It uses a global variable to track login status and redirects users to a login page if they are not authenticated. ```javascript var isLoggedIn = false var Login = { view: function() { return m("form", [ m("button[type=button]", { onclick: function() { isLoggedIn = true m.route.set("/secret") } }, "Login") ]) } } m.route(document.body, "/secret", { "/secret": { onmatch: function() { if (!isLoggedIn) m.route.set("/login") else return Home } }, "/login": Login }) ``` -------------------------------- ### Navigate to a Route with Parameters Source: https://github.com/mithriljs/docs/blob/main/docs/route.md Navigates to a specified route, interpolating parameters into the path. This example demonstrates setting a route with a dynamic `articleid` parameter. ```javascript var Article = { view: function(vnode) { return "This is article " + vnode.attrs.articleid } } m.route(document.body, "/article/1", { "/article/:articleid": Article }) m.route.set("/article/:articleid", {articleid: 1}) ``` -------------------------------- ### Preload Data with oninit Hook Source: https://github.com/mithriljs/docs/blob/main/docs/route.md This example demonstrates preloading data using the `oninit` hook. The component renders twice: once initially showing 'loading', and again after the data request completes. ```javascript var state = { users: [], loadUsers: function() { return m.request("/api/v1/users").then(function(users) { state.users = users }) } } m.route(document.body, "/user/list", { "/user/list": { oninit: state.loadUsers, view: function() { return state.users.length > 0 ? state.users.map(function(user) { return m("div", user.id) }) : "loading" } }, }) ``` -------------------------------- ### Implement Authentication with Token Storage Source: https://github.com/mithriljs/docs/blob/main/docs/route.md This example demonstrates a more robust authentication flow using a token stored in localStorage. It includes input fields for username and password and makes a request to an authentication API. ```javascript var Auth = { username: "", password: "", setUsername: function(value) { Auth.username = value }, setPassword: function(value) { Auth.password = value }, login: function() { m.request({ url: "/api/v1/auth", params: {username: Auth.username, password: Auth.password} }).then(function(data) { localStorage.setItem("auth-token", data.token) m.route.set("/secret") }) } } var Login = { view: function() { return m("form", [ m("input[type=text]", { oninput: function (e) { Auth.setUsername(e.target.value) }, value: Auth.username }), m("input[type=password]", { oninput: function (e) { Auth.setPassword(e.target.value) }, value: Auth.password }), m("button[type=button]", {onclick: Auth.login}, "Login") ]) } } m.route(document.body, "/secret", { "/secret": { onmatch: function() { if (!localStorage.getItem("auth-token")) m.route.set("/login") else return Home } }, "/login": Login }) ``` -------------------------------- ### Configure npm Test Script Source: https://github.com/mithriljs/docs/blob/main/docs/testing.md Add a 'test' script to your package.json to run ospec tests, optionally requiring a setup file. ```json { "name": "my-project", "scripts": { "test": "ospec --require ./test-setup.js" } } ``` -------------------------------- ### Parse URL with Query Parameters Source: https://github.com/mithriljs/docs/blob/main/docs/parsePathname.md This example demonstrates parsing a URL with multiple query parameters. The resulting 'params' object will contain all key-value pairs from the query string. ```javascript var data = m.parsePathname("/path/user?a=hello&b=world") // data.path is "/path/user" // data.params is {a: "hello", b: "world"} ``` -------------------------------- ### A-Frame Example with Hyperscript Source: https://github.com/mithriljs/docs/blob/main/docs/hyperscript.md Demonstrates using Mithril.js hyperscript to create complex nested structures for custom elements like A-Frame components. ```javascript m("a-scene", [ m("a-box", { position: "-1 0.5 -3", rotation: "0 45 0", color: "#4CC3D9", }), m("a-sphere", { position: "0 1.25 -5", radius: "1.25", color: "#EF2D5E", }), m("a-cylinder", { position: "1 0.75 -3", height: "1.5", color: "#FFC65D", }), m("a-plane", { position: "0 0 -4", rotation: "-90 0 0", width: "4", height: "4", color: "#7BC8A4", }), m("a-sky", { color: "#ECECEC", }), ]) ``` -------------------------------- ### Preload Data with RouteResolver and render Source: https://github.com/mithriljs/docs/blob/main/docs/route.md This example uses `onmatch` and `render` to preload data before rendering, avoiding the need for a loading indicator. The `render` function only executes after the data request is complete. ```javascript var state = { users: [], loadUsers: function() { return m.request("/api/v1/users").then(function(users) { state.users = users }) } } m.route(document.body, "/user/list", { "/user/list": { onmatch: state.loadUsers, render: function() { return state.users.map(function(user) { return m("div", user.id) }) } }, }) ``` -------------------------------- ### Mithril.js Component Examples Source: https://context7.com/mithriljs/docs/llms.txt Demonstrates different ways to define components in Mithril.js, including POJO, closure, and ES6 class components. Also shows passing data via attributes and separating model logic. ```javascript // POJO component var Button = { view: function(vnode) { return m("button", {onclick: vnode.attrs.onclick}, vnode.attrs.label) } } m(Button, {label: "Save", onclick: function() { save() }}) // Closure component with local state function Counter(initialVnode) { var count = initialVnode.attrs.start || 0 function increment() { count++ } function decrement() { count-- } return { view: function() { return m("div", [ m("button", {onclick: decrement}, "-"), m("span", " " + count + " "), m("button", {onclick: increment}, "+"), ]) } } } m.mount(document.body, {view: function() { return m(Counter, {start: 5}) }}) // ES6 class component class TodoItem { constructor(vnode) { this.done = false } toggle() { this.done = !this.done } view(vnode) { return m("li", { style: {textDecoration: this.done ? "line-through" : "none"}, onclick: () => this.toggle() }, vnode.attrs.text) } } m(TodoItem, {text: "Buy groceries"}) // Passing data via attrs; separating model from view var Auth = { username: "", password: "", setUsername: function(v) { Auth.username = v }, setPassword: function(v) { Auth.password = v }, canSubmit: function() { return Auth.username && Auth.password }, login: function() { return m.request({method: "POST", url: "/api/login", body: Auth}) .then(function(res) { localStorage.setItem("token", res.token) m.route.set("/dashboard") }) } } var LoginForm = { view: function() { return m("form", [ m("input[type=text]", { oninput: function(e) { Auth.setUsername(e.target.value) }, value: Auth.username, placeholder: "Username" }), m("input[type=password]", { oninput: function(e) { Auth.setPassword(e.target.value) }, value: Auth.password, placeholder: "Password" }), m("button", {disabled: !Auth.canSubmit(), onclick: Auth.login}, "Login") ]) } } ``` -------------------------------- ### Input Binding: v1.x vs v2.x Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v1x.md Illustrates the difference in binding input values in v1.x using `m.withAttr` versus v2.x direct assignment. Both examples show handling of string and stream-based values. ```javascript var value = "" // In your view m("input[type=text]", { value: value(), oninput: m.withAttr("value", function(v) { value = v }) }) // OR var value = m.stream("") // In your view m("input[type=text]", { value: value(), oninput: m.withAttr("value", value), }) ``` ```javascript var value = "" // In your view m("input[type=text]", { value: value, oninput: function (ev) { value = ev.target.value }, }) // OR var value = m.stream("") // In your view m("input[type=text]", { value: value(), oninput: function (ev) { value(ev.target.value) }, }) ``` -------------------------------- ### Mount Mithril Component Source: https://github.com/mithriljs/docs/blob/main/docs/index.md Mount a simple Mithril component to the document body. This example demonstrates basic component mounting and rendering a heading. ```javascript var root = document.body // Your code here m.mount(root, { view: function() { return m("h1", "Try me out") } }) ``` -------------------------------- ### Mithril.js Application Routing Setup Source: https://github.com/mithriljs/docs/blob/main/docs/simple-application.md Sets up client-side routing for a Mithril.js application. Use this to define different views for different URL paths and to pass route parameters to components. ```javascript // src/index.js var m = require("mithril") var UserList = require("./views/UserList") var UserForm = require("./views/UserForm") var Layout = require("./views/Layout") m.route(document.body, "/list", { "/list": { render: function() { return m(Layout, m(UserList)) } }, "/edit/:id": { render: function(vnode) { return m(Layout, m(UserForm, vnode.attrs)) } }, }) ``` -------------------------------- ### m.buildPathname() Usage Source: https://github.com/mithriljs/docs/blob/main/docs/buildPathname.md This example demonstrates how to use m.buildPathname() to create a URL string from a path template and a query object. The function takes a path string and an object containing parameters, returning a fully formed URL. ```APIDOC ## m.buildPathname(path, query) ### Description Turns a [path template](paths.md) and a parameters object into a string of form `/path/user?a=1&b=2`. ### Signature `pathname = m.buildPathname(path, query)` Argument | Type | Required | Description ------------ | ------------------------------------------ | -------- | --- `path` | `String` | Yes | A URL path `query ` | `Object` | Yes | A key-value map to be converted into a string **returns** | `String` | | A string representing the URL with the query string ### Example ```javascript var pathname = m.buildPathname("/path/:id", {id: "user", a: "1", b: "2"}) // "/path/user?a=1&b=2" ``` ### How it works The `m.buildPathname` creates a [path name](paths.md) from a path template and a parameters object. It's useful for building URLs, and it's what [`m.route`](route.md) and [`m.request`](request.md) use internally to interpolate paths. It uses [`m.buildQueryString`](buildQueryString.md) to generate the query parameters to append to the path name. ```javascript var pathname = m.buildPathname("/path/:id", {id: "user", a: 1, b: 2}) // pathname is "/path/user?a=1&b=2" ``` ``` -------------------------------- ### Initialize Application with Basic Routing Source: https://github.com/mithriljs/docs/blob/main/docs/simple-application.md Sets up the main application entry point, requiring necessary modules and configuring the initial route for the user list. ```javascript var m = require("mithril") var UserList = require("./views/UserList") var UserForm = require("./views/UserForm") m.route(document.body, "/list", { "/list": UserList }) ``` -------------------------------- ### Build Documentation Source: https://github.com/mithriljs/docs/blob/main/CONTRIBUTING.md Executes the build process for the documentation. ```bash npm run build ``` -------------------------------- ### v0.2.x: Get and Set Current Route Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v02x.md In v0.2.x, both getting and setting the current route were handled by the `m.route()` function. ```javascript // Getting the current route m.route() // Setting a new route m.route("/other/route") ``` -------------------------------- ### Initialize npm Project Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Initialize a new npm project if a package.json file does not exist. ```bash # Replace this with the actual path to your project. Quote it if it has spaces, # and single-quote it if you're on Linux/Mac and it contains a `$$` anywhere. cd "/path/to/your/project" # If you have a `package.json` there already, skip this command. npm init ``` -------------------------------- ### Initialize npm project Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Initializes the current directory as an npm package. This is the first step for setting up a project with esbuild. ```bash $ npm init --yes ``` -------------------------------- ### Create index.js for Mithril app Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Basic Mithril.js application entry point that renders 'hello world' to the DOM. Requires Mithril to be imported. ```javascript import m from "mithril"; m.render(document.getElementById("app"), "hello world"); ``` -------------------------------- ### Component Initialization in Mithril.js v2.x (using oninit) Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v02x.md Shows how to use the `oninit` lifecycle method in v2.x components to initialize state, replacing the `controller` function from v0.2.x. State is accessed via `vnode.state` or `this`. ```javascript m.mount(document.body, { oninit: function(vnode) { vnode.state.fooga = 1 }, view: function(vnode) { return m("p", vnode.state.fooga) } }) // OR m.mount(document.body, { // this is bound to vnode.state by default oninit: function(vnode) { this.fooga = 1 }, view: function(vnode) { return m("p", this.fooga) } }) ``` -------------------------------- ### Initialize npm Project Source: https://github.com/mithriljs/docs/blob/main/docs/simple-application.md Initializes a new npm project in the current directory. This command creates a `package.json` file, which is essential for managing project dependencies and metadata. ```bash npm init -y ``` -------------------------------- ### Successful Test Output Source: https://github.com/mithriljs/docs/blob/main/docs/testing.md Example output indicating that all tests have passed successfully. ```text –––––– All 1 assertions passed in 0ms ``` -------------------------------- ### Develop Build Source: https://github.com/mithriljs/docs/blob/main/docs/contributing.md Generate the bundled file for development and testing purposes. ```bash npm run dev ``` -------------------------------- ### Example Mithril.js Component Source: https://github.com/mithriljs/docs/blob/main/docs/testing.md A simple Mithril.js component that renders a div with provided text content. ```javascript function MyComponent() { return { view: function (vnode) { return m("div", vnode.attrs.text) } } } module.exports = MyComponent ``` -------------------------------- ### Get the current route Source: https://github.com/mithriljs/docs/blob/main/docs/api.md Retrieve the current route string from the application's router using `m.route.get()`. ```javascript var currentRoute = m.route.get() ``` -------------------------------- ### CSS Fade-out Animation for Removal Source: https://github.com/mithriljs/docs/blob/main/docs/animation.md Define a CSS class for an exit animation. This example creates a fade-out effect. ```css .exit {animation:fade-out 0.5s;} @keyframes fade-out { from {opacity:1;} to {opacity:0;} } ``` -------------------------------- ### Consuming Class Components Source: https://github.com/mithriljs/docs/blob/main/docs/components.md Demonstrates various ways to consume class components, including rendering with `m.render`, mounting with `m.mount`, and routing with `m.route`. ```javascript // EXAMPLE: via m.render m.render(document.body, m(ClassComponent)) // EXAMPLE: via m.mount m.mount(document.body, ClassComponent) // EXAMPLE: via m.route m.route(document.body, "/", { "/": ClassComponent }) ``` -------------------------------- ### Basic Stream Usage Source: https://github.com/mithriljs/docs/blob/main/docs/stream.md Streams can hold state and act as getter-setters. They are functions that can be called to get or set their value. ```javascript var username = stream("John") console.log(username()) // logs "John" username("John Doe") console.log(username()) // logs "John Doe" ``` ```javascript var users = stream() // request users from a server using the fetch API fetch("/api/users") .then(function(response) {return response.json()}) .then(users) ``` -------------------------------- ### v2.x: Get and Set Current Route Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v02x.md In v2.x, route management is split into `m.route.get()` for retrieval and `m.route.set()` for navigation. ```javascript // Getting the current route m.route.get() // Setting a new route m.route.set("/other/route") ``` -------------------------------- ### Configure Babel .babelrc Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Set up the .babelrc file to use @babel/preset-env for transpilation and enable source maps. ```json { "presets": ["@babel/preset-env"], "sourceMaps": true } ``` -------------------------------- ### CSS Fade-in Animation Source: https://github.com/mithriljs/docs/blob/main/docs/animation.md Define a CSS class with an animation for element creation. This example uses a simple fade-in effect. ```css .fancy {animation:fade-in 0.5s;} @keyframes fade-in { from {opacity:0;} to {opacity:1;} } ``` -------------------------------- ### Render 'Hello world' Text Source: https://github.com/mithriljs/docs/blob/main/docs/index.md Use `m.render` to display simple text content on the screen. This function efficiently updates the DOM. ```javascript var root = document.body m.render(root, "Hello world") ``` -------------------------------- ### m.request() Usage Source: https://github.com/mithriljs/docs/blob/main/docs/request.md Makes XHR (aka AJAX) requests, and returns a promise. This example demonstrates a PUT request to update a user. ```APIDOC ## PUT /api/v1/users/:id ### Description Makes an XHR request to update a specific user. ### Method PUT ### Endpoint /api/v1/users/:id ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the user to update. #### Request Body - **name** (string) - Required - The new name for the user. ### Request Example ```javascript m.request({ method: "PUT", url: "/api/v1/users/:id", params: {id: 1}, body: {name: "test"} }) .then(function(result) { console.log(result) }) ``` ### Response #### Success Response (200) - **result** (any) - The response from the server. ``` -------------------------------- ### Parse query string with leading question mark Source: https://github.com/mithriljs/docs/blob/main/docs/parseQueryString.md Shows that the method correctly handles query strings that start with a question mark. ```javascript var data = m.parseQueryString("?a=hello&b=world") // data is {a: "hello", b: "world"} ``` -------------------------------- ### Include Mithril.js via CDN Source: https://github.com/mithriljs/docs/blob/main/docs/installation.md Use this script tag to include Mithril.js directly from a CDN for simple setups or quick testing. ```html ``` -------------------------------- ### Sample Lifecycle Hooks in Component and Vnode Source: https://github.com/mithriljs/docs/blob/main/docs/lifecycle-methods.md Demonstrates how to define and use lifecycle hooks like `oninit` within a Mithril component and directly on a vnode. Lifecycle methods are called as a side effect of `m.render()`. ```javascript var ComponentWithHook = { oninit: function(vnode) { console.log("initialize component") }, view: function() { return "hello" } } function initializeVnode() { console.log("initialize vnode") } m(ComponentWithHook, {oninit: initializeVnode}) ``` -------------------------------- ### Using JSX Components Source: https://github.com/mithriljs/docs/blob/main/docs/jsx.md Demonstrates how to render Mithril components using JSX, including both custom components and built-in ones like m.route.Link. ```jsx m.render(document.body, ) // equivalent to m.render(document.body, m(MyComponent)) Go home // equivalent to m(m.route.Link, {href: "/home"}, "Go home") ``` -------------------------------- ### Compile Source to Distribution Directory Source: https://github.com/mithriljs/docs/blob/main/docs/es6.md Use the Babel CLI to transpile code from the src directory to the dist directory. ```bash babel src --out-dir dist ``` -------------------------------- ### v0.2.x: Accessing Route Parameters Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v02x.md In v0.2.x, route parameters were exclusively accessed using `m.route.param()`. This example shows its usage within controller and view functions. ```javascript m.route(document.body, "/booga", { "/:attr": { controller: function() { m.route.param("attr") // "booga" }, view: function() { m.route.param("attr") // "booga" } } }) ``` -------------------------------- ### Request with Explicit Query String Source: https://github.com/mithriljs/docs/blob/main/docs/paths.md Sends a server request where the query string is explicitly defined in the URL, and parameters are provided separately. This is equivalent to the previous example. ```javascript m.request({ url: "https://example.com/api/user/:userID/connections?sort=name-asc", params: { userID: 1 } }) ``` -------------------------------- ### Get Current Route Source: https://github.com/mithriljs/docs/blob/main/docs/route.md Retrieves the last fully resolved routing path. This may differ from the URL in the address bar if an asynchronous route is currently pending. ```javascript path = m.route.get() ``` -------------------------------- ### Routing Mode Configuration in v2.x Source: https://github.com/mithriljs/docs/blob/main/docs/migration-v02x.md Demonstrates how to configure the routing mode in v2.x using `m.route.prefix`, which replaces the `m.route.mode` property from v0.2.x. ```javascript m.route.mode = "hash" m.route.mode = "pathname" m.route.mode = "search" ``` ```javascript // Direct equivalents m.route.prefix = "#" m.route.prefix = "" m.route.prefix = "?" ``` -------------------------------- ### RouteResolver Example with onmatch and render Source: https://github.com/mithriljs/docs/blob/main/docs/route.md Defines a RouteResolver object with onmatch to return a component and render to display it. This is a common pattern when integrating components with Mithril's routing. ```javascript var routeResolver = { onmatch: function() { return Home }, render: function(vnode) { return [vnode] }, } ```