[Backbone] Parse JSON on Collection

// Get /appointments
{
"per_page": 10, "page": 1, "total": 50,
"appointments": [
{ "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
]
}



The server team is at it again, but this time they at least have a good reason: they want to start paginating appointments instead of just returning all of them when we fetch the collection. No problem. We've been here before. Take a look at the JSON the server is responding with below, and then modify the  function to set properties on the collection instance for , , and .Appointmentsparseper_pagetotalpage
var Appointments = Backbone.Collection.extend({
  parse: function(response){
    this.per_page = response.per_page;
    this.total = response.total;
    this.page = response.page;
    return response;
  }
});

Fantastic work! Now to finish the job, just return the appointments array from the parse function, instead of the entire response.javascript

// Get /appointments
{
  "per_page": 10, "page": 1, "total": 50,
  "appointments": [
    { "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
  ]
}
var Appointments = Backbone.Collection.extend({
  parse: function(response){
    this.perPage = response.per_page;
    this.page = response.page;
    this.total = response.total;
    response = response.appointments
    return response;
  }
});

The server team has implemented a feature for limiting the appointments pulled down based on the appointment date. In the code below, update the fetch call to pass an extra param so that the URL is like:/appointments?since=2013-01-01html

var appointments = new Appointments();
appointments.fetch({data: {since: '2013-01-01'}});

We can limit the number of appointments returned by passing in a per_page parameter also. Go ahead and construct the fetch call below to create a URL that looks like /appointments?since=2013-01-01&per_page=10java

var appointments = new Appointments();
appointments.fetch({data: {since: "2013-01-01", per_page: 10}});

Let's start to implement this feature by adding a template to the AppointmentListView below. The template should have a link that looks like this: <a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>app

var AppointmentListView = Backbone.View.extend({
    //Using template display the Next page
    template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
    initialize: function(){
        this.collection.on('reset', this.render, this);
    },
    render: function(){
        thi.$el.empty();
        this.collection.forEach(this.addOne, this);
    },
    addOne: function(model){
        var appointmentView = new AppointmentView({model: model});
        appointmentView.render();
        this.$el.append(appointmentView.el);
    }
});

let's add some code in the render function to append the generated HTML from the template into the AppointmentListView $el. Make sure you pass in thepage and per_page properties to the template function, getting those values fromthis.collection.page + 1 and this.collection.per_page respectively.ide

var AppointmentListView = Backbone.View.extend({
  template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
  initialize: function(){
    this.collection.on('reset', this.render, this);
  },
  render: function(){
    this.$el.empty();
    this.collection.forEach(this.addOne, this);
    this.$el.append(this.template({page:this.collection.page + 1, per_page:this.collection.per_page}));
  },
  addOne: function(model){
    var appointmentView = new AppointmentView({model: model});
    appointmentView.render();
    this.$el.append(appointmentView.el);
  }
});

Now that we are rendering the link, we need to implement the route to handleappointments/p:page/pp:per_page and have the route function fetch the new appointments based on the parameters. Name this new function page.fetch

var AppRouter = new (Backbone.Router.extend({
  routes: { 
    "": "index",
    "appointments/p:page/pp:per_page": "page"
  },
  initialize: function(options){
    this.appointmentList = new AppointmentList();
  },
  index: function(){
    var appointmentsView = new AppointmentListView({collection: this.appointmentList});
    appointmentsView.render();
    $('#app').html(appointmentsView.el);
    this.appointmentList.fetch();
  },
  page: function(page, per_page){
    this.appointmentList.fetch({data:{page: page, per_page: per_page}});
  }
}));

 

Our appointments are being rendered in a pretty haphazard way. Dr. Goodparts is very chronological, so we need to always have our appointments sorted by the date. Add the code below to accomplish this.this

var Appointments = Backbone.Collection.extend({
  comparator: "date"
});
var app1 = new Appointment({date: "2013-01-01"});
var app2 = new Appointment({date: "2013-02-01"});
var app3 = new Appointment({date: "2013-01-15"});
var app4 = new Appointment({date: "2013-01-09"});
var appointments = new Appointments();
appointments.add(app1);
appointments.add(app2);
appointments.add(app3);
appointments.add(app4);

Dr. Goodparts just sent us this email "Love the new sorting, but please flip it and reverse it", Update the comparator below to sort by date in reverse orderatom

var Appointments = Backbone.Collection.extend({
  comparator: function(ap1, ap2){
      return ap1.get('date') < ap2.get('date');
  }
});

 implement a function on the collection to count up the number of cancelled appointments. Implement this function in the collection class below and call it cancelledCount.spa

var Appointments = Backbone.Collection.extend({
  cancelledCount: function(){
    return this.where({'cancelled': true}).length;
  }
});

 

 

----------------------------Final Code------------------------code

var Appointments = Backbone.Collection.extend({
 // comparator: "date",
  comparator: function(ap1, ap2){
      return ap1.get('date') < ap2.get('date');
  },
   cancelledCount: function(){
    return this.where({'cancelled': true}).length;
  }, 
  parse: function(response){
    this.perPage = response.per_page;
    this.page = response.page;
    this.total = response.total;
    response = response.appointments
    return response;
  }
});
var appointments = new Appointments();
appointments.fetch({data: {since: "2013-01-01", per_page: 10}});
var AppointmentListView = Backbone.View.extend({
  template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
  initialize: function(){
    this.collection.on('reset', this.render, this);
  },
  render: function(){
    this.$el.empty();
    this.collection.forEach(this.addOne, this);
    this.$el.append(this.template({page:this.collection.page + 1, per_page:this.collection.per_page}));
  },
  addOne: function(model){
    var appointmentView = new AppointmentView({model: model});
    appointmentView.render();
    this.$el.append(appointmentView.el);
  }
});
var AppRouter = new (Backbone.Router.extend({
  routes: { 
    "": "index",
    "appointments/p:page/pp:per_page": "page"
  },
  initialize: function(options){
    this.appointmentList = new AppointmentList();
  },
  index: function(){
    var appointmentsView = new AppointmentListView({collection: this.appointmentList});
    appointmentsView.render();
    $('#app').html(appointmentsView.el);
    this.appointmentList.fetch();
  },
  page: function(page, per_page){
    this.appointmentList.fetch({data:{page: page, per_page: per_page}});
  }
}));
相關文章
相關標籤/搜索