Model updates

"So Shawn, instead of using the Backbone collection in an isolated fashion, let's move it to a class to manage adding of new cats randomly and provide it with some other utilities, as follows:"

const PictureModel = Backbone.Model.extend({
  defaults: {
    src: 'http://lorempixel.com/601/600/cats/',
    name: 'Pusheen',
    details: 'Pusheen is a Cat',
    faved: false
  }
});

"Our PictureModel stays the same. We are adding a new faved attribute here to maintain state about whether the cat was faved by the user or not.

"We will call this new class of ours CatGenerator, which will provide the component that we use to display the cats, with the data to display, fetch, and add new cats."

"Got it. Want me to give it a try?"

"Sure."

import Backbone from 'backbone';
import Faker from 'faker';
import _ from 'underscore';
…

class CatGenerator {
  constructor() {
    this.Cats = new Backbone.Collection;
    [600, 601, 602, 603, 604, 605].map( (height)=>{
      this.createCat(height, 600);
    })
  }

  createCat(height = _.random(600, 650), width = 600) {
    console.log('Adding new cat');
    this.Cats.add(new PictureModel({
      src: `http://lorempixel.com/${height}/${width}/cats/`,
      name: Faker.Name.findName(),
      details: Faker.Lorem.paragraph()
    }));
  }
}

"Nice Shawn."

"Thanks. I moved createCat as a method of its own so that we can add cats to the collection on the fly. I am just adding a random one right now, taking a random height of 600-650 and a random width to create a new PictureModel instance."

"Also, to start with, I am creating cats collection as an attribute on the class. Next, I have added six cats to begin with."

"Cool. We are now going to start changing its use in our Components."

Tip

Remember that we are going to update the components when new data comes in. Easy way to do this is to start storing the CatGenerator as a state object on the Home component.

"Let's start defining and changing our Home component, as follows:"

class Home extends React.Component {
  constructor() {
    super();
    this.timer = null;
    this.state = {catGenerator: new CatGenerator()};
  }

  componentDidMount() {
    this.timer = setInterval(::this.generateCats, 1000);
  }

  generateCats() {
    let catGenerator = this.state.catGenerator;
    catGenerator.createCat();
    clearInterval(this.timer);
    this.timer = setInterval(::this.generateCats, catGenerator.randRange());

    this.setState({catGenerator: catGenerator});
  }
…

"So, what we are doing here is creating a timer to track time intervals. We are going to use a random time interval to simulate the addition of a new stream of cats here."

"Got it," followed up Shawn.

"To do this, I have added the generateCats() method. In our componentDidMount, we are adding and setting the timer to call this method after the first creation."

"In the method itself, I have added clearing of the old interval and we are calling the catGenerator.createCat() method to actually create the cat from our CatGenerator class."

"We are then resetting the timer and setting a new one, based on a random time interval. I added the catGenerator.randRange() method to generate the random time interval. Here's how it looks in the CatGenerator class:"

randRange() {
    return _.random(5000, 10000);
  }

"Got it. This should be creating a new stream of cats in the range of 5-10 seconds."

"Next, let's take a look at how our render method looks. I am going to add a star next to the cats."

render() {
    let Cats = this.state.catGenerator.Cats;

    return (
        <div>
          <div>

              {Cats.map(cat => (
                  <div key={cat.cid} style={{float: 'left'}}>
                    <Link to={`/pictures/${cat.cid}`}
                          state={{ modal: true, returnTo: this.props.location.pathname, cat: cat }}>
                      <img style={{ margin: 10 }} src={cat.get('src')} height="100"/>
                    </Link>
                    <span key={`${cat.cid}`} className="fa fa-star"></span>
                  </div>
              ))}

          </div>
        </div>
    )
  }

"There are two changes that I am doing here. First of all, I added the star, which is unfaved by default."

                    <span key={`${cat.cid}`} className="fa fa-star"></span>

"Secondly, I started passing the cat object on the modal link's state."

                    <Link to={`/pictures/${cat.cid}`}
                          state={{ modal: true, 
                                       returnTo: this.props.location.pathname,  
                                       cat: cat }}>

"In our PictureModel box, we previously had the access to the global collection of cats. From now on, that won't be the case and we would need the cat object to be passed to the Picture component."

"That's neat, we are able to pass the objects too, to the component from a router <Link/> object."

"Yup, let's go ahead and change the picture component in order for it to work properly with this new change in passing the data. Our Modal stays the same:"

const Modal = React.createClass({
  styles: {
…   
  },

  render() {
     return (
      <div style={this.styles}>
        <p><Link to={this.props.returnTo}>Back</Link></p>
        {this.props.children}
      </div>
    )
  }
})
…
export {Modal as default}

"The Picture component now starts using the cat object."

import React from 'react'
import { PictureModel } from './models';

const Picture = React.createClass({
  render() {
    let { location } = this.props;
    let cat = location.state.cat;
    console.log(this.props);
    return (
        <div>
          <div style={{ float: 'left', width: '40%' }}>
            <img src={cat.get('src')} style={{ height: '80%' }}/>
          </div>
          <div style={{ float: 'left', width: '60%' }}>
            <h3>Name: {cat.get('name')}.</h3>
            <p>Details: {cat.get('details')} </p>
          </div>
        </div>
    )
  }
});

export {Picture as default}

"As you can see, the cat object is received on the location.state object from props."

"I have extended the picture to display more details about the cat, such as the name and so on, instead of showing it on a separate page. Previously, it looked pretty blank."

"Cool, let's take a look at how it looks, shall we?"

Model updates

"Nice, the stars look good. We will need to check the styles that I added for this soon."

"The modal seems to be looking good as well, and look at all these cats being generated as a stream!"

"Nice!" Mike and Shawn rejoiced.

Model updates
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.235.215