简体   繁体   English

骨干获取URL参数

[英]Backbone get URL parameter

I have a Backbone js app that runs when I go to the URL domain.com/item/1 or domain/item/2` etc. When the app starts I create a new instance of my model and pass it an id which needs to be the last part of the URL. 我有一个Backbone js应用程序,当我转到URL domain.com/item/1或domain / item / 2`等时运行。当该应用程序启动时,我将创建模型的新实例并将其传递给ID是网址的最后一部分。 Is there a way to access this in Backbone? 有没有办法在骨干网中访问它?

I know it's easy to build a router that can access parameters after a hash so I am better of changing my URL to be something like domain.com/item/1#1 ? 我知道构建一个可以在哈希后访问参数的路由器很容易,因此我最好将URL更改为domain.com/item/1#1

I don't know you have a backbone router or not.But that's easily achievable by one of the basic use of Backbone.router . 我不知道您是否有骨干路由器,但这可以通过Backbone.router的基本用法之一轻松实现。 and you do not have to use # or anything.You can access anything between slashes. 而且您不必使用#或其他任何内容。您可以在斜杠之间访问任何内容。

routes: {
  "item/:page":  function(page){
      //page holds the query parameter.
    }
}

The routes hash maps URLs with parameters to functions on your router (or just direct function definitions, if you prefer), similar to the View's events hash. 路由哈希将带有参数的URL映射到路由器上的功能(如果愿意,也可以直接映射功能),类似于View的事件哈希。 Routes can contain parameter parts, :param, which match a single URL component between slashes; 路由可以包含参数部分:param,它们与斜杠之间的单个URL组件匹配; and splat parts *splat, which can match any number of URL components. 和splat部分* splat,可以匹配任意数量的URL组件。 Part of a route can be made optional by surrounding it in parentheses (/:optional). 路由的一部分可以通过将其括在圆括号中来使其为可选(/:optional)。

Please read the section of Backbone.router in the documentation for detail. 请阅读文档中Backbone.router的部分以获取详细信息。

http://backbonejs.org/#Router http://backbonejs.org/#Router

FYI, passing the query parameter to your model should not be executed when a user start app but when routes is called.otherwise everytime you want to change page,You need to change url and reload the whole page. 仅供参考,在用户启动应用程序时,不应在调用routes时执行将查询参数传递给模型的操作。否则,每次要更改页面时,都需要更改url并重新加载整个页面。

and usually Controller makes model instances which means,You'd better create controller instance with parameters in router and then create a model in the controller.something like this 通常,Controller会创建模型实例,这意味着,最好在router使用参数创建控制器实例,然后在控制器中创建模型。

routes: {
  "item/:page":  function(page){
      var page = new YourNameSpace.Controller.Foo({pageId : page});
      page.render();
    }
}

//inside of Itempage Controller
initialize : function(){
  this.model = new YourNameSpace.Model.Foo({pageId : this.pageId});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM