如何从URL获取ID

时间:2013-05-09 17:56:37

标签: backbone.js marionette

我正在开发Backbone Marionette网络应用程序。 我这个应用程序我得到了这样的路线:

projects/:id/tasks

如何获取该路线的ID(URL)?

如果我使用这个,我会得到整个网址:

Backbone.history.fragment

更新

这是我定义项目路线的方式。

@Projectapp.module "ProjectsApp", (ProjectsApp, App, Backbone, Marionette, $, _) ->

    class ProjectsApp.Router extends Marionette.AppRouter
        appRoutes:
            "projects/new" : "newProject"
            "projects/:id" : "showProject"
            "projects/:id/edit" : "editProject"
            "projects" : "listProjects"

    API =
        listProjects: ->
            new ProjectsApp.List.Controller

        newProject: ->
            new ProjectsApp.New.Controller

        showProject: (id, project) ->
            new ProjectsApp.Show.Controller
                id: id
                project: project

        editProject: (id, project) ->
            new ProjectsApp.Edit.Controller
                id: id
                project: project

    App.Router.on "route:newProject", (project_id) ->
        alert project_id

    App.commands.setHandler "new:crew:member", (region) ->
        API.newCrew region

    App.vent.on "project:new:clicked", (project) ->
        App.navigate "projects/new", true

    App.vent.on "project:tasks:clicked", (project) ->
        App.navigate "projects/#{project.id}/tasks", true

    App.vent.on "project:created", (project) ->
        App.navigate "projects/#{project.id}", true

    App.vent.on "project:show:clicked project:back:clicked", (project) ->
        App.navigate "projects/#{project.id}"
        API.showProject project.id, project

    App.vent.on "project:clicked project:edit:clicked", (project) ->
        App.navigate "projects/#{project.id}/edit"
        API.editProject project.id, project

    App.vent.on "project:cancelled project:list:back:clicked", (project) ->
        App.navigate "projects"
        API.listProjects()

    App.addInitializer ->
        new ProjectsApp.Router
            controller: API

2 个答案:

答案 0 :(得分:2)

路由器将为您的处理函数提供从URL解析的属性。

您有一个使用"projects/:id" : "showProject"定义的路线,但您的处理程序是

showProject: (id, project) ->
        new ProjectsApp.Show.Controller
            id: id
            project: project

它们不匹配:您的路由器将从URL发送已解析的id,但就是这样。在将项目传递给视图之前,您需要自己获取项目,例如:

showProject: (id) ->
        project = @projects_collection.get id
        new ProjectsApp.Show.Controller
            id: id
            project: project

当然,这意味着您需要能够访问项目集合,或者获取项目等。

答案 1 :(得分:1)

路由器的定义应与此类似(例如):

var Router = Backbone.Router.extend({

    routes:{
        "page/:number":"go_to_page",
        "show_something":"show_something"
    },

});

然后,您可以将路由事件绑定到接受路由变量的函数,例如:

Router.on("route:go_to_page",function(page) {
   // page parameter corresponds to :number in the url hash, so now you can query your models with this string.
});

希望这个例子有帮助...