### Install Dependencies with Bundler Source: https://github.com/derbyjs/derby/blob/master/docs/README.md Navigate to the docs directory and install Jekyll and its dependencies using Bundler. ```bash cd docs && bundle install ``` -------------------------------- ### Start Existing Docker Docs Server Source: https://github.com/derbyjs/derby/blob/master/docs/README.md Start the previously created Docker container to run the Jekyll development server. This command assumes the container 'derby-docs-ruby' has already been created. ```bash docker start -i derby-docs-ruby ``` -------------------------------- ### Path Examples for Model Data Source: https://github.com/derbyjs/derby/blob/master/docs/models/paths.md Demonstrates various path strings and the corresponding data they reference within the example model structure. Note the use of dot notation for object properties and numeric indices for array elements. ```text - '_page', referring to the object { currentStorefrontId: 'storefront-1' } - 'storefronts.storefront-a.title', referring to the title of "storefront-a" - 'storefronts.storefront-a.fruits.0', referring to the first fruit object in "storefront-a" ``` -------------------------------- ### File Structure Example Source: https://github.com/derbyjs/derby/blob/master/docs/views/namespaces-and-files.md Demonstrates a typical file structure where view namespaces correspond to directories and files, and how imports create equivalent nested namespaces. ```jinja #### index.html ```jinja App ``` #### about/index.html ```jinja About - App ``` #### about/mission.html ```jinja Mission statement - App ``` would be equivalent to: `index.html` ```jinja App About - App Mission statement - App ``` ``` -------------------------------- ### Start Named Reactive Function in Route Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md This example demonstrates starting a named reactive function ('topPlayers') within a route handler. It sets up input paths and the output path, ensuring the function updates reactively. ```javascript app.get('/leaderboard/:gameId', function(page, model, params, next) { var game = model.at('game.' + params.gameId); game.subscribe(function(err) { if (err) return next(err); game.setNull('players', [ {name: 'John', score: 4000}, {name: 'Bill', score: 600}, {name: 'Kim', score: 9000}, {name: 'Megan', score: 3000}, {name: 'Sam', score: 2000} ]); model.set('_page.cutoff', 3); model.start( '_page.topPlayers', game.at('players'), '_page.cutoff', 'topPlayers' ); page.render(); }); }); ``` -------------------------------- ### Example Usage in Component `init` Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md Demonstrates how to use `model.start` (which internally uses reactive functions) within a component's `init` method to create a reactive sum of two values. ```APIDOC ## Component Initialization with Reactive Functions ### Description Reactive functions are typically set up in the `init` method of a DerbyJS component. This ensures they are established on both the server and the client, and are automatically cleaned up when the component is unmounted. ### Example ```js MyComponent.prototype.init = function(model) { // Sets up a reactive function to calculate the sum of 'first' and 'second' // The 'total' path will be updated whenever 'first' or 'second' changes. model.start('total', ['first', 'second'], function sum(x, y) { return (x || 0) + (y || 0); }); }; ``` ### Notes - `model.start` is a convenience method that internally uses `model.evaluate`. - Reactive functions are automatically stopped when the component is destroyed. ``` -------------------------------- ### Define a GET Route Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `app.get` to define a route that handles GET requests. The callback function is executed on both server and client. ```javascript app.get ( '/', function (page, model, params, next) { // Render the home page page.render('home'); }); ``` -------------------------------- ### Using Custom Attribute Tags Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Provides examples of how to use the custom 'tabs' tag with different attribute syntaxes. ```jinja {{0}} Hello! Greetings. ``` -------------------------------- ### Start Reactive Function Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md Immediately evaluates the function, sets the returned value to the output path, and sets up listeners to re-evaluate when input paths change. Use this for continuous updates. ```javascript value = model.start(path, inputPaths, [options], fn) ``` -------------------------------- ### Legacy Start Reactive Function Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md The legacy syntax for starting a reactive function, used in versions prior to racer 0.9.5. It accepts a variable number of input paths. ```javascript // Legacy (racer <= 0.9.5) value = model.start(path, inputPaths..., [options], fn) ``` -------------------------------- ### Create Docker Container for Docs Build Source: https://github.com/derbyjs/derby/blob/master/docs/README.md One-time setup to create a Docker container for building and serving the Derby.js docs. It maps the local 'docs' directory into the container and exposes port 4000. ```bash docker run --name derby-docs-ruby -v "$(pwd)/docs:/derby-docs" -p 127.0.0.1:4000:4000 ruby:2.7 bash -c 'cd derby-docs && bundle install && bundle exec jekyll serve -H 0.0.0.0 -P 4000 --trace' ``` -------------------------------- ### Create and Use Scoped Models Source: https://github.com/derbyjs/derby/blob/master/docs/models/paths.md Demonstrates creating a scoped model using `model.at()` and shows equivalent ways to set and get data using both the scoped model and the original model. Also illustrates logging the model's content. ```javascript const roomModel = model.at('_page.room'); // These are equivalent: roomModel.at('name').set('Fun room'); roomModel.set('name', 'Fun room'); // Logs: {name: 'Fun room'} console.log(roomModel.get()); // Logs: 'Fun room' console.log(roomModel.get('name')); ``` -------------------------------- ### Call component, page, and global functions Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/functions-and-events.md Functions are looked up on the component controller, page, and global scope in that order. This example shows calling a component method, a page utility function, and a global method. ```html {{sum(1, 2, 4)}} {{console.log('rendering value', value)}} ``` -------------------------------- ### Handle custom component events Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/functions-and-events.md Components can emit custom events. Dashes in event names are transformed into camelCase. This example shows how to listen for `close` and `fullView` events. ```html ``` -------------------------------- ### Start a reactive function in DerbyJS Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md Establish a persistent reactive function using `model.start` within a component's `init` method. This function will update a specified output path whenever its input paths change. It's automatically managed and stopped when the component is destroyed. ```javascript MyComponent.prototype.init = function(model) { model.start('total', ['first', 'second'], function sum(x, y) { return (x || 0) + (y || 0); }); }; ``` -------------------------------- ### Serve Docs Locally with Jekyll Source: https://github.com/derbyjs/derby/blob/master/docs/README.md Run the Jekyll development server to build and serve the documentation site. Changes to source files will trigger auto-rebuilds. ```bash bundle exec jekyll serve ``` -------------------------------- ### Invalid HTML Structure Example Source: https://github.com/derbyjs/derby/blob/master/docs/guides/troubleshooting.md This example illustrates invalid HTML syntax that can cause Derby.js to fail attaching bindings due to browser parsing differences. Ensure HTML adheres to standards to prevent structure mismatches between server and client rendering. ```html

``` ```html
``` -------------------------------- ### Run Unit Tests Source: https://github.com/derbyjs/derby/blob/master/README.md Execute the project's unit tests using npm. ```bash npm test ``` -------------------------------- ### ShareDB Mongo Document Structure (Object Type) Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Example of a ShareDB document stored as a direct Mongo document when the data is an object. ```json { "make": "Ford", "model": "Mustang", "year": 1969, "_m": { "ctime": 1494381632731, "mtime": 1494381635994 }, "_type": "http://sharejs.org/types/JSONv0", "_v": 12 } ``` -------------------------------- ### Two-way Binding with NOT Operator Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/operators.md The NOT operator supports two-way data binding, allowing it to be used for both getting and setting boolean values, commonly used with checkboxes. ```html ``` -------------------------------- ### Create Backend with MongoDB and Redis Pub/Sub Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Configure a production environment with multiple frontend servers using Redis for pub/sub operations. Requires Redis 2.6+. ```js var derby = require('derby'); var ShareDbMongo = require('sharedb-mongo'); var RedisPubSub = require('sharedb-redis-pubsub'); var db = new ShareDbMongo('mongodb://localhost:27017/test'); var backend = derby.createBackend({ db: db, pubsub: new RedisPubSub() }); var model = backend.createModel(); ``` -------------------------------- ### Use Deprecated Relative Paths with 'this' Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/paths.md Relative paths, starting with `this`, refer to the expression in the containing block. This syntax is deprecated and aliases are preferred for clarity. ```jinja {{with user}}

{{this.name}}

{{this.headline}}

{{if this.friendList}}

Friends

    {{each this}}
  • {{this.name}}
  • {{/each}}
{{/if}} {{/with}} ``` -------------------------------- ### Run Browser Tests Source: https://github.com/derbyjs/derby/blob/master/README.md Execute front-end tests in a browser. This command will prompt to open a browser. ```bash npm run test-browser ``` -------------------------------- ### ShareDB Mongo Document Structure (Other OT Types) Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Example of a ShareDB document stored under the '_data' property when using other OT types like Plaintext. ```json { "_data": "This is a text message.", "_m": { "ctime": 1494381632731, "mtime": 1494381635994 }, "_type": "http://sharejs.org/types/text", "_v": 12 } ``` -------------------------------- ### Racer Path to Database Mapping Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Illustrates the natural mapping between Racer paths and database collections, documents, and properties. ```bash collection.documentId.documentProperty ``` -------------------------------- ### Pass a scoped model to a function Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/functions-and-events.md Use `$at()` to pass a scoped model to a function instead of just its value. This allows the function to directly get or set the model's value. ```html ``` -------------------------------- ### Create Backend with MongoDB Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Use this for a single-process server with MongoDB storage. It sets up a ShareDB-Mongo database connection and creates a Derby backend. ```js var derby = require('derby'); var ShareDbMongo = require('sharedb-mongo'); var db = new ShareDbMongo('mongodb://localhost:27017/test'); var backend = derby.createBackend({db: db}); var model = backend.createModel(); ``` -------------------------------- ### Attach event listeners with 'on-' attributes Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Attributes starting with 'on-' are used to attach event listeners to component events. Refer to the Component Events documentation for more details on usage. ```jinja ``` -------------------------------- ### Define a 'within' attribute in a dropdown component Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md This example shows how to define a 'within' attribute for the `content` attribute in a dropdown component. The `{{@content}}` will be rendered using the context provided by the parent view. ```jinja
    {{each @options as #option, #i}}
  • {{@content}}
  • {{/each}}
``` -------------------------------- ### Basic Literal Attribute Values Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Demonstrates using string literals, multi-word attribute names, numeric literals, and boolean attributes. ```jinja Hello, World. ``` -------------------------------- ### Validate HTML for Derby Templates Source: https://github.com/derbyjs/derby/blob/master/docs/components/lifecycle.md This example demonstrates how to check if an HTML string will produce a consistent innerHTML value after being parsed and re-serialized. This is crucial for ensuring Derby templates are valid and deterministic. ```javascript var html = '

'; var div = document.createElement('div'); div.innerHTML = html; html === div.innerHTML; ``` -------------------------------- ### Creating Array Attributes with Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Shows how to use the `` tag to create an array of objects for an attribute, where each HTML tag represents an object. ```jinja Hello! Greetings. ``` -------------------------------- ### Instantiating Views in Derby Templates Source: https://github.com/derbyjs/derby/blob/master/docs/views.md Shows various methods for using registered views within a Derby template, including the recommended tag, self-closing syntax, expression form, and custom tag names. ```jinja

Hello, sir.

{{view 'serious-title'}} ``` -------------------------------- ### Example Derby Model Data Structure Source: https://github.com/derbyjs/derby/blob/master/docs/models/paths.md This JSON object illustrates the structure of data that can be managed by a Derby model. Paths are used to reference specific values or nested objects within this structure. ```json { _page: { currentStorefrontId: 'storefront-1' }, storefronts: { 'storefront-a': { id: 'storefront-a', title: 'Fruit store', fruits: [ { name: 'banana', color: 'yellow' }, { name: 'apple', color: 'red' }, { name: 'lime', color: 'green' } ] } } } ``` -------------------------------- ### Define and Use Aliases with 'as #' Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/paths.md Create aliases for path expressions using the `as` keyword, prefixed with a hash (`#`). Aliases improve clarity and allow referencing current or parent scopes. ```jinja {{with user as #user}}

{{#user.name}}

{{#user.headline}}

{{if #user.friendList as #friendList}}

Friends of {{#user.name}}

    {{each #friendList as #friend}}
  • {{#friend.name}}
  • {{/each}}
{{/if}} {{/with}} ``` -------------------------------- ### Create a Query Object Source: https://github.com/derbyjs/derby/blob/master/docs/models/queries.md Instantiate a query object by providing the collection name and a database-specific query. This object represents the data you want to fetch or subscribe to. ```javascript const query = model.query(collectionName, databaseQuery) ``` -------------------------------- ### Remove Items from an Array in Derby.js Model Source: https://github.com/derbyjs/derby/blob/master/docs/models/mutators.md Use `model.remove` to remove a specified number of items from an array starting at a given index. The `howMany` argument is optional and defaults to 1. It returns an array of the removed items. ```javascript model.remove(path, index, [howMany], [callback]) ``` -------------------------------- ### Manually Create a Model Source: https://github.com/derbyjs/derby/blob/master/docs/models.md Create a model instance directly on the server outside of a request context using `backend.createModel()`. Options can be passed to control its behavior, such as `fetchOnly`. ```javascript const model = backend.createModel(options); ``` -------------------------------- ### Async/Await Subscribe with Multiple Items Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Demonstrates using async/await with the promise-based subscribe API to handle multiple data subscriptions. Errors are caught using a try-catch block. ```javascript // Promise-based API with async/await try { await model.subscribePromised([userModel, todosQuery]); console.log(userModel.get(), todosQuery.get()); } catch (error) { // Handle subscribe error } ``` -------------------------------- ### Throttle calls to at most once per 75ms Source: https://github.com/derbyjs/derby/blob/master/docs/components/component-class.md Use `component.throttle` to limit function calls to a maximum frequency, suitable for continuous event streams like scrolling. This example limits `update` calls to once every 75 milliseconds. ```javascript class MyComponent extends Component { create() { // Call this.update() at most once every 75 milliseconds this.dom.on('scroll', window, this.throttle(this.update, 75)); } update() { // Update based on scroll location } } ``` -------------------------------- ### Define Named Reactive Function on Model Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md Reactive functions started on the server via a name are reinitialized when the page loads. Use the 'model' event emitted by apps to add functions for use in routes as well as on the client. ```javascript app.on('model', function(model) { model.fn('topPlayers', function(players, cutoff) { return players.slice().sort(function (a, b) { return a.score - b.score; }).slice(0, cutoff - 1); }); }); ``` -------------------------------- ### Navigate Back in History Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `app.history.back` as a shortcut to call `window.history.back()`, simulating a click on the browser's back button. ```javascript app.history.back() ``` -------------------------------- ### Mutating Projected Documents Source: https://github.com/derbyjs/derby/blob/master/docs/guides/troubleshooting.md When a document is loaded with a projection, mutations must use the same projection name. For example, if loaded with `notes_title.note-12`, mutate using `model.set('notes_title.note-12.title', 'Intro')`. Using the base collection name will cause an error. ```javascript model.fetch('notes_title.note-12') ``` ```javascript model.set('notes_title.note-12.title', 'Intro') ``` ```javascript model.set('notes.note-12.title') ``` -------------------------------- ### Importing Index Files Source: https://github.com/derbyjs/derby/blob/master/docs/views/namespaces-and-files.md An `index.html` file can be imported via the name of its containing directory. The name `index` can be used for a view returned for the namespace name itself. ```jinja #### index.html ```jinja ``` #### home.html ```jinja

Hello! ``` ``` -------------------------------- ### Create a Derby App Source: https://github.com/derbyjs/derby/blob/master/docs/apps.md Use `derby.createApp` to create a new app instance. The app name is used to associate templates and styles. The created app object is typically exported. ```javascript var app = derby.createApp ( name, fileName ) module.exports = app ``` -------------------------------- ### Move Items within an Array in Derby.js Model Source: https://github.com/derbyjs/derby/blob/master/docs/models/mutators.md Use `model.move` to relocate items within an array from a starting index to a new index. The `howMany` argument specifies the number of items to move and defaults to 1. It returns an array of the moved items. ```javascript model.move(path, from, to, [howMany], [callback]) ``` -------------------------------- ### Render a View Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `page.render` to display a specific view. Refer to the documentation on namespaces and files for view naming conventions. ```javascript page.render(viewName) ``` -------------------------------- ### Attribute Values with Expressions Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Shows how to use path expressions, bracket expressions, operator expressions, and complex expressions for attribute values. ```jinja {{modalBody}} ``` -------------------------------- ### Create Derby Backend Source: https://github.com/derbyjs/derby/blob/master/docs/models.md Instantiate a Racer backend for your Derby.js project. Refer to the Backends section for detailed configuration options. ```javascript backend = derby.createBackend(options) ``` ```javascript backend = racer.createBackend(options) ``` -------------------------------- ### Registering Views with Derby HTML Source: https://github.com/derbyjs/derby/blob/master/docs/views.md This demonstrates how Derby HTML template syntax for defining views is parsed into calls to app.views.register(). ```jinja

Hello, sir.

Howdy!

``` ```js app.views.register('serious-title', '

Hello, sir.

'); app.views.register('friendly-title', '

Howdy!

'); ``` -------------------------------- ### Loading Data into Model Source: https://github.com/derbyjs/derby/blob/master/docs/guides/troubleshooting.md To perform mutations on a DB-backed document, it must first be loaded into the model. This can be done by fetching or subscribing to the document via its ID or a query, or by creating a new document using `model.add()`. ```javascript model.add() ``` -------------------------------- ### Confirming Model Updates with Callbacks and Promises Source: https://github.com/derbyjs/derby/blob/master/docs/models/mutators.md Demonstrates how to handle model mutations using both the traditional callback API and the modern Promise API. Use callbacks for older code or simpler async handling, and promises for more complex asynchronous flows or when using async/await. ```javascript // Callback API model.set('note-1.title', 'Hello world', (error) => { if (error) { return handleError(error); } console.log('Update successful!'); }); ``` ```javascript // Promise API try { await model.setPromised('note-1.title', 'Hello world'); } catch (error) { return handleError(error); } console.log('Update successful!'); ``` -------------------------------- ### Passing Control with next() Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Call `next()` to pass control to the next matching route. If no other routes match, it will fall through to a server request. ```javascript app.get ( '/about', function (page, model, params, next) { // Check if user is logged in, if not, redirect if (!model.get('user.isLoggedIn')) { return page.redirect('/login'); } page.render('about'); }); app.get ( '/about', function (page, model, params, next) { // This route is only reached if the previous one didn't render or redirect next(); }); ``` -------------------------------- ### Using Tag for HTML Templates Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Demonstrates an alternative syntax using the `` tag to pass HTML templates to specific attributes. ```jinja Introducing, {{modalTitle}} , World. ``` -------------------------------- ### View Namespaces Source: https://github.com/derbyjs/derby/blob/master/docs/views/namespaces-and-files.md View names use colon-separated namespaces for encapsulation. Lookups are relative to the current namespace. ```jinja ... ... ``` -------------------------------- ### model.evaluate Source: https://github.com/derbyjs/derby/blob/master/docs/models/reactive-functions.md Sets up a reactive function that updates a value at a specified path based on changes in input paths. The function is executed with the values of the input paths. ```APIDOC ## model.evaluate ### Description Creates a reactive binding where the value at `path` is updated by calling `fn` with the values from `inputPaths`. The binding is automatically removed when the component is destroyed. ### Method Signature `model.evaluate(path, inputPaths, [options], fn)` ### Parameters #### `path` - **Type**: `string | ChildModel` - **Description**: The output path at which to set the value, keeping it updated as input paths change. #### `inputPaths` - **Type**: `Array` - **Description**: One or more paths whose values will be retrieved from the model and passed to the function as inputs. #### `options` (optional) - **Type**: `Object` - **Description**: Configuration options for the reactive function. - **`copy`** (string): Controls automatic deep copying of the inputs to the function. - `'input'`: Deep-copy the inputs to the function. - `'none'`: Do not automatically copy anything (default behavior). #### `fn` - **Type**: `Function | string` - **Description**: A function or the name of a function defined via `model.fn()` that will be called with the input path values. See `model.start` docs for details. ### Return Value - **Type**: `any` - **Description**: The value returned by the function. ``` -------------------------------- ### Comparison Operators Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/operators.md Use comparison operators to compare values. Supported operators include strict equality (===), strict inequality (!==), loose equality (==), loose inequality (!=), less than (<), greater than (>), less than or equal (<=), and greater than or equal (>=). ```jinja {{left === right}} ``` ```jinja {{left !== right}} ``` ```jinja {{left == right}} ``` ```jinja {{left != right}} ``` ```jinja {{left < right}} ``` ```jinja {{left > right}} ``` ```jinja {{left <= right}} ``` ```jinja {{left >= right}} ``` -------------------------------- ### Valid Template Expression Placements Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax.md Shows correct ways to use template expressions within text, attribute values, and surrounding elements or text. ```jinja Let's go {{activity}}! Let's go running! {{if maybe}} Let's go dancing! {{/if}} ``` -------------------------------- ### Subscribe to a Single Document Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Demonstrates subscribing to a single document using its path string. Access the data using model.get() after the subscription is complete. ```javascript // Subscribing to a single document with a path string. const userPath = `users.${userId}`; model.subscribe(userPath, (error) => { if (err) return next(err); console.log(model.get(userPath)); }); ``` -------------------------------- ### Fetch Multiple Queries (Callback API) Source: https://github.com/derbyjs/derby/blob/master/docs/models/queries.md Run multiple queries concurrently using the model's fetch method with a callback. This allows for efficient loading of various data sets. ```javascript model.fetch([query1, query2], (error) => { if (error) throw error // All query data loaded into the model }) ``` -------------------------------- ### View Partial Scope Inheritance Source: https://github.com/derbyjs/derby/blob/master/docs/components/view-partials.md Demonstrates how a view partial inherits scope from its instantiation point. The 'my-partial' inherits 'foo' from the parent and '#bar' from the 'with' block. ```jinja {{foo}} {{with #root.bar as #bar}} {{/with}} i can render {{foo}} and {{#bar}} ``` -------------------------------- ### Select Views Dynamically Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/escaping.md Dynamically select which view to render based on a variable. This allows for flexible UI generation without resorting to unescaped HTML. ```jinja ``` -------------------------------- ### Define a POST Route Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `app.post` to define a route that handles POST requests. This is useful for form submissions. ```javascript app.post ( '/users', function (page, model, params, next) { // Create a new user model.submit(function(m) { m.at('users').push(params.user); }); next(); }); ``` -------------------------------- ### Create Request Models with Middleware Source: https://github.com/derbyjs/derby/blob/master/docs/models.md Use `backend.modelMiddleware()` to attach a new model to `req.model` for each incoming request. Subsequent middleware can then modify this model before it's used for rendering. ```javascript expressApp.use(backend.modelMiddleware()); expressApp.use((req, res, next) => { req.model.set('_session.userId', 'test-user'); next(); }); derbyApp.use(derbyApp.router()); ``` -------------------------------- ### Access 'as-object' mapped elements in controller Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md This JavaScript code shows how to set up data and then access elements mapped using 'as-object'. 'this.listItems.a' directly references the element associated with the ID 'a'. ```javascript this.page.model.set('_page.items', [ {id: 'a', name: 'Item A'}, {id: 'b', name: 'Item B'}, ]); this.listItems.a // references the Component or DOM element for "Item A" ``` -------------------------------- ### Navigate Forward in History Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `view.history.forward` as a shortcut to call `window.history.forward()`, simulating a click on the browser's forward button. ```javascript view.history.forward() ``` -------------------------------- ### HTML Templates as Attribute Values Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Illustrates passing HTML templates, including conditional and loop structures, as attribute values. ```jinja , World. ``` -------------------------------- ### Dynamic View Lookup in Derby Templates Source: https://github.com/derbyjs/derby/blob/master/docs/views.md Illustrates how to dynamically select and render a view based on an expression within a Derby template, falling back to rendering nothing if the view is not found. ```jinja {{view type + '-title'}} ``` -------------------------------- ### Singleton Component Data Binding Source: https://github.com/derbyjs/derby/blob/master/docs/guides/troubleshooting.md When using singleton components, local model paths like `{{value}}` will fail. Bind data via attributes and use attribute paths `{{@value}}` instead. Alternatively, consider using plain view partials if component controller functions are not needed. ```html {{@value}} ``` -------------------------------- ### Setting Nested Undefined Paths Source: https://github.com/derbyjs/derby/blob/master/docs/models/mutators.md Demonstrates how to set a value at a deeply nested path, which will automatically create parent objects or arrays if they do not exist. ```javascript model.set('cars.DeLorean.DMC12.color', 'silver'); // Logs: { cars: { DeLorean: { DMC12: { color: 'silver' }}}} ``` -------------------------------- ### Use a Singleton Component in a View Source: https://github.com/derbyjs/derby/blob/master/docs/components/lifecycle.md Render a singleton component in a view using the `` tag. Attributes prefixed with `@` are supported in singleton component views, as they do not have their own model. ```jinja
{{getInitials(@user.fullName)}}
``` -------------------------------- ### Call Peer Component Methods using `as=` Source: https://github.com/derbyjs/derby/blob/master/docs/components/events.md Use the `as=` attribute to expose a component instance as a property on the current controller. This allows events on one component to trigger methods on another. ```jinja ``` ```jinja ... ``` -------------------------------- ### Subscribe to Change Events with Wildcards Source: https://github.com/derbyjs/derby/blob/master/docs/models/events.md This snippet demonstrates how to subscribe to change events on a path with wildcards, like tracking the completion status of todos. The callback receives captured segments from the path and the new value. ```javascript model.on('change', 'todos.*.completed', function(todoId, isComplete) { ... }); ``` -------------------------------- ### Subscribe and Reference Query Results (Promise API) Source: https://github.com/derbyjs/derby/blob/master/docs/models/queries.md This snippet is for frontend code using the Promise API (racer@1.1.0+) to subscribe to query results and create a live-updating model reference. It demonstrates asynchronous handling of subscriptions and accessing results. ```javascript const notesQuery = model.query('notes', { creatorId: userId }); // Frontend code usually subscribes. // Subscribing to multiple things in parallel reduces the number of round-trips. try { await model.subscribePromised([notesQuery, `users.${userId}`]); } catch (error) { return handleError(error); } // Add a reference to the query results to get automatic UI updates. // A view can use these query results with {{#root._page.notesQueryResults}}. notesQuery.ref('_page.notesQueryResults'); // Controller code can get the results either with the query or with the ref. console.log(notesQuery.get()); console.log(model.get('_page.notesQueryResults')); // Backend-only code usually only needs to fetch. try { await notesQuery.fetchPromised(); } catch (error) { console.log(notesQuery.get()); } ``` -------------------------------- ### Model Reference Input and Output Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Shows how to use model references for two-way data binding. These attributes reflect changes in both directions between the view and the model. ```html value="{{inputText}}" value="{{todos[#id].text}}" ``` -------------------------------- ### Page Rendering and Redirection Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Methods available on the `page` object for rendering views, rendering static content, and handling redirects. ```APIDOC ## page.render ( viewName ) ### Description Renders the specified view. ### Parameters #### Path Parameters - **viewName** (string) - Required - The name of the view to render. ## page.renderStatic ( statusCode, content ) ### Description Renders static HTML content with a specified HTTP status code. ### Parameters #### Path Parameters - **statusCode** (number) - Required - The HTTP status code to return. - **content** (string) - Required - A string of HTML to render. ## page.redirect ( url, [status] ) ### Description Redirects the user to a new URL. ### Parameters #### Path Parameters - **url** (string) - Required - Destination of redirect. Can be 'home' or 'back'. - **status** (number) - Optional - Number specifying HTTP status code. Defaults to 302 on the server. ``` -------------------------------- ### Subscribe to Multiple Items Source: https://github.com/derbyjs/derby/blob/master/docs/models/backends.md Shows how to subscribe to multiple data items simultaneously, including a document via a child model and a query. Access the data for all subscribed items after the callback. ```javascript // Subscribing to two things at once: a document via child model and a query. const userModel = model.at(userPath); const todosQuery = model.query('todos', {creatorId: userId}); model.subscribe([userModel, todosQuery], function(err) { if (err) return next(err); console.log(userModel.get(), todosQuery.get()); }); ``` -------------------------------- ### Re-rendering on Path Change with On Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/blocks.md Use 'on' to explicitly control re-rendering of a section based on changes to specified paths. Useful for optimizing performance or managing complex bindings. ```jinja {{on #profile.id}}

{{#profile.name}}

{{/on}} {{on first, second, third}} {{/on}} ``` -------------------------------- ### Importing Views from Files Source: https://github.com/derbyjs/derby/blob/master/docs/views/namespaces-and-files.md Include views from other files using the `` tag. The `src` attribute supports relative paths or paths to `node_modules`. ```jinja ``` -------------------------------- ### Map items to keys with 'as-object' Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md The 'as-object' attribute creates a map-like object in the controller, where each entry is keyed by a specified value (e.g., '#item.id'). This allows direct access to elements based on their unique identifiers. ```jinja
    {{each _page.items as #item}}
  • {{#item.name}}
  • {{/each}}
``` -------------------------------- ### Todos Footer Component Source: https://github.com/derbyjs/derby/blob/master/docs/components.md Displays the count of remaining todos. This component is marked as a singleton, meaning only one instance will be rendered. ```jinja ``` -------------------------------- ### Redirect to a URL Source: https://github.com/derbyjs/derby/blob/master/docs/routes.md Use `page.redirect` to navigate the user to a new URL. It supports special values like 'home' and 'back', and an optional status code on the server. ```javascript page.redirect(url, [status]) ``` -------------------------------- ### Create and Use Model References Source: https://github.com/derbyjs/derby/blob/master/docs/models/refs.md Use `model.ref` to create a reference to another model path. Setting properties on the reference path modifies the underlying data. Removing the reference does not affect the original data. ```javascript model.set('colors', { red: {hex: '#f00'} , green: {hex: '#0f0'} , blue: {hex: '#00f'} }); // Getting a reference returns the referenced data model.ref('_page.green', 'colors.green'); // Logs {hex: '#0f0'} console.log(model.get('_page.green')); // Setting a property of the reference path modifies // the underlying data model.set('_page.green.rgb', [0, 255, 0]); // Logs {hex: '#0f0', rgb: [0, 255, 0]} console.log(model.get('colors.green')); // Removing the reference has no effect on the underlying data model.removeRef('_page.green'); // Logs undefined console.log(model.get('_page.green')); // Logs {hex: '#0f0', rgb: [0, 255, 0]} console.log(model.get('colors.green')); ``` -------------------------------- ### Fetch Query Results (Callback API) Source: https://github.com/derbyjs/derby/blob/master/docs/models/queries.md Use the callback API to fetch query results. The callback function is executed once the data is loaded or if an error occurs. ```javascript query.fetch((error) => { if (error) throw error // Query data loaded into the model }) ``` -------------------------------- ### Listen to Model Mutations with Path Patterns Source: https://github.com/derbyjs/derby/blob/master/docs/models/events.md Use `model.on()` to subscribe to specific mutation events like 'change', 'insert', or 'remove'. Filter events by providing a path pattern, which can include single segment ('*') or multi-segment ('**') wildcards. The `**` wildcard is only valid at the end of the path or by itself. ```javascript listener = model.on(method, path, [options], eventCallback) ``` -------------------------------- ### Listen to Change Events with Wildcards and Event Objects Source: https://github.com/derbyjs/derby/blob/master/docs/models/events.md This snippet demonstrates how to listen for changes to specific properties within a nested structure using wildcards and event objects. It logs the captured path segment and the new value. Requires `{useEventObjects: true}`. ```javascript model.on('change', 'todos.*.completed', {useEventObjects: true}, function(changeEvent, captures) { console.log('todos.' + captures[0] + ' set to ' + changeEvent.value); }); ``` -------------------------------- ### Attribute Binding Input Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/view-attributes.md Illustrates using attribute bindings for dynamic input values, such as boolean conditions or default labels. These are primarily one-way inputs, recomputing the value as dependencies change. ```html disabled="{{!active}}" label="{{userLabel || 'User'}}" list="{{reverse(items)}}" options="{{ {speed: currentSpeed} }}" ``` -------------------------------- ### Component with View Attributes Source: https://github.com/derbyjs/derby/blob/master/docs/components/scope.md Demonstrates passing data and literals as view attributes to a component and accessing them within the component's template. ```html
    {{each data as #user}}
  • {{#user.name}}
  • {{/each}}
{{num + 10}} ``` -------------------------------- ### Create and use a named context for data loading Source: https://github.com/derbyjs/derby/blob/master/docs/models/contexts.md Create a child model with a named context to isolate data loading operations. Use `subscribe` to fetch data and `set` to update state within this context. Call `unload` with the context name to release the data when it's no longer needed. ```javascript function openTodos(model) { // Create a model with a load context inheriting from the current model var dialogModel = model.context('todosDialog'); // Load data var userId = dialogModel.scope('_session.userId').get(); var user = dialogModel.scope('users.' + userId); var todosQuery = dialogModel.query('todos', {creatorId: userId}); dialogModel.subscribe(user, todosQuery, function(err) { if (err) throw err; // Delay display until required data is loaded dialogModel.set('showTodos', true); }); } function closeTodos(model) { model.set('showTodos', false); // Use the same context name to unsubscribe model.unload('todosDialog'); } ``` -------------------------------- ### Conditional Rendering with If/Else If/Else Source: https://github.com/derbyjs/derby/blob/master/docs/views/template-syntax/blocks.md Use 'if', 'else if', and 'else' to conditionally render template sections based on truthy or falsey values. Zero-length arrays are treated as falsey. ```jinja {{if user.name}}

user.name

{{else if user}}

Unnamed user

{{else}} No user {{/if}} ```