Derived Properties

In notebook:
Building Modern Web Apps
Created at:
2016-01-27
Updated:
2016-01-28
Tags:
libraries JavaScript React Ampersand
We need to dynamically build the urls for repos/repo_url

app_url as a derived property of the model. so it's easy to link to that page anywhere in that app.
In models/repo.js
  // ****     repo.js    ****
import Model from 'ampersand-model'

export default Model.extend({
    props: {
        id: 'number',
        name: 'string',
        full_name: 'string'
    }
    
    // ++++ 1. add the derived property
    derived: {
        appUrl: {
            // deps are the properties it's dependent on
            deps: ['full_name'],
            // use fn() for the function to generate it
            fn () {
                return '/' + this.full_name
            }
        }
    }
    
})
This also creates a change notifier for this property that you can listen to.

For example a touch event library, it's great to be able to define this properties declaratively. Like a movement of a touch: the distance of the movement can be a derived property. And then just listen to this change event, to know something is moving or not).
Derived properties can be dependent on each other.

Models mimic plain javascript object

For React, all these models are simple (plain) objects. This means you can use it on the server-side to pre-render the pages.
So now we can use ​repo.appUrl​ in our layout.
  // ****     pages/repos.js      ****
import React form 'react'
import ampersandMixin from 'ampersan-react-mixin'

export default React.createClass({
    mixins: ampersandMixin,
    
    render () {
        const {repos} = this.props
    
        return (
            <div>
                <h2>Repos</h2>
                <ul>
                    {repos.map( repo => {
                        return (<li key={repo.id}>
                        <span className="octicon octicon-repo">
                        // ++++ 1. add the url
                        </span><a href="{repo.appUrl}">{repo.full_name}</a>
                        </li>
                        )
                    })}
                </ul>
            </div>
        )
    }
    
})
The state doesn't get automatically hotloaded (the repo model appUrl)

- Are Ampersand models easy to test?
- Yes very easy, work without a browser