1

我正在开发一个 Backbone Marionette 网络应用程序。在这个应用程序中,我得到了如下所示的路线:

projects/:id/tasks

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

如果我使用它,我会得到整个 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
4

2 回答 2

2

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

您定义了一条路线,"projects/:id" : "showProject"但您的处理程序是

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

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

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

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

于 2013-05-15T07:23:49.543 回答
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.
});

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

于 2013-05-09T18:06:54.280 回答