zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

[Backbone] App orgianztation

App Backbone
2023-09-14 08:59:21 时间

Time to get organized. Dr. Goodparts really hates global scope and has ordered that we only have at most 1 object polluting his precious global scope.

Create an object that contains an empty CollectionsModels, and Views object. Name the top-level objectAppointmentApp.

var AppointmentApp = {
  Views: {},
  Models: {},
  Collections: {}
};

 

Now that we have our new top-level object, change our class definitions below to use it. Make sure you clean up the names of the views by removing View since it's not needed anymore. Assign the AppRouter right on theAppointmentApp object.

var AppointmentApp = {
  Collections: {},
  Models: {},
  Views: {}
}

AppointmentApp.Models.Appointment = Backbone.Model.extend({});
AppointmentApp.Collections.Appointments = Backbone.Collection.extend({});
AppointmentApp.Views.Appointment = Backbone.View.extend({});
AppointmentApp.Views.Appointments = Backbone.View.extend({});
AppointmentApp.AppRouter = new (Backbone.Router.extend({}))();

 

Turn the AppointmentApp object into a Backbone view instance. That means that you'll have to immediately instantiate the Backbone.View class returned by Backbone.View.extend().

var AppointmentApp = new (Backbone.View.extend({
  Collections: {},
  Models: {},
  Views: {}
}))({el: document.body});

 

In our new App view, add an event to capture all clicks on a tags that have the data-backbone attribute on them. In the event handler, prevent the default event and use Backbone.history.navigate to pass the link through our app's router. Don't forget to pass in trigger: true.

var AppointmentApp = new (Backbone.View.extend({
  Collections: {},
  Models: {},
  Views: {},
  events:{
    'click a[data-backbone]': function(e){
        e.preventDefault();
      Backbone.history.navigate(e.target.pathname, {trigger: true});
    },
  }
}))({el: document.body});

 

Dr. Goodparts wants his appointment app to load faster so the server team included some bootstrap data on the page that you can use to bootstrap your Appointments collection instead of using fetch. Modify the start function in theAppointmentApp to receive this data as a parameter and pass in the appointments bootstrap data to theAppointments() constructor.

var AppointmentApp = new (Backbone.View.extend({
  Collections: {},
  Models: {},
  Views: {},
  events: {
    'click a[data-backbone]': function(e){
      e.preventDefault();
      Backbone.history.navigate(e.target.pathname, { trigger: true });
    }
  },
  start: function(appointments){
    this.appointments = new AppointmentApp.Collections.Appointments(appointments.appointments);
    var appointmentsView = new AppointmentApp.Views.Appointments({collection: this.appointments});
    $('#app').html(appointmentsView.render().el);
    //this.appointments.fetch();
  }
}))({el: document.body});