zoukankan      html  css  js  c++  java
  • [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 Appointmentscollection. No problem. We've been here before. Take a look at the JSON the server is responding with below, and then modify the parse function to set properties on the collection instance for per_pagetotal, and page.
    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.

    // 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-01

    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=10

    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>

    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.

    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.

    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.

    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 order

    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.

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

    ----------------------------Final 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}});
      }
    }));
  • 相关阅读:
    删除顺序表L中下标为p(0<=p<=length-1)的元素,成功返回1,不成功返回0,并将删除元素的值赋给e
    设顺序表中的数据元素递增有序,试着写一算法,将x插入到顺序表上的适当位置上,以保持该表的有序性。
    数据结构-顺序表基本操作的实现(含全部代码)【转】
    【转】结构体指针
    结构体(第十四章 )
    线性表
    第二章 c语言概述
    时间复杂度
    软件质量与测试 黑盒测试
    软件质量保证与测试 基本内容
  • 原文地址:https://www.cnblogs.com/Answer1215/p/3897868.html
Copyright © 2011-2022 走看看