[Backbone]Real Route

本文介绍如何优化Backbone.js中的路由配置,包括处理可选参数、解码URL参数、限制参数类型及设置捕获所有路由的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Duplication is Bad. Let's DRY (Don't Repeat Yourself) our routes to make /pp:per_page an optional part of the pageroute.

var AppRouter = new (Backbone.Router.extend({
  routes: {
    "appointments/p:page(/pp:per_page)": "page"
  },
  page: function(page, per_page){
    per_page = per_page || 10;

    this.appointments.fetch({data: {page: page, per_page: per_page}});
  }
}));

 

Dr. Goodparts has the bad habit of typing out his URL's with a trailing slash and now he's upset that our routes don't work. Please update the route below to optionally accept an optional trailing slash

var AppRouter = new (Backbone.Router.extend({
  routes: {
    "appointments/p:page(/pp:per_page)(/)": "page"
  },
  page: function(page, per_page){
    per_page = per_page || 10;

    this.appointments.fetch({data: {page: page, per_page: per_page}});
  }
}));

 

The Server Team is at it again and has added the ability to select a page and the per page using natural language. So instead of page 25, they can now accept "twenty five". Our page route function should work as is but it needs to be able to handle encoded params. To fix this, decode the page and per_page params in the page function.

var AppRouter = new (Backbone.Router.extend({
  routes: {
    "appointments/p:page(/pp:per_page)(/)": "page"
  },
  page: function(page, per_page){
    page  = decodeURIComponent(page);
     per_page  = decodeURIComponent(per_page);
    this.appointments.fetch({data: {page: page, per_page: per_page}});
  }
}));

 

Rewrite the show route to only accept numeric input for the id parameter. You'll have to add the initialize function to the AppRouter and use a regular expression.

var AppRouter = new (Backbone.Router.extend({
  routes: {
    "appointments/:id":  "show"
  },
  show: function(id){
    var appointment = new Appointment({id: id});
    console.log(appointment);
  }
}));
AppRouter.route(/{d}*/);

 

Just in case people fiddle around with the URL let's add a catch-all route to our router that will log out to the console. Make sure the catch-all route comes last.

var AppRouter = new (Backbone.Router.extend({
  routes: {
    "appointments/:id":  "show",
    "*path": "notFound"
  },
  show: function(id){
    var appointment = new Appointment({id: id});
    console.log(appointment);
  },
  notFound: function(path){
      console.log("not found");
  }
}));
AppRouter.navigate('notthinghere', {trigger: true});

 

转载于:https://www.cnblogs.com/Answer1215/p/3900164.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值