【问题标题】:Running an Backbone app as an independent JS application - Routes not working将 Backbone 应用程序作为独立的 JS 应用程序运行 - 路由不起作用
【发布时间】:2013-01-05 10:13:53
【问题描述】:

目前,我将骨干网作为 Rails 3.2 应用程序的前端运行。我需要将它迁移到一个独立的 JS 应用程序中,作为我将它作为 Trigger.io 的一部分的一部分。

它现在作为自己的 index.html 文件存在,引用 assets 文件夹。

当我打开文件时,它会加载 Backbone 模块,但页面仍然是空的。当我运行 fetch() 命令时,它

所以,我得到了几个 qns:


1) 如何触发路由使其默认跳转到指定页面?

我知道它会在 Backbone.History.Start 中触发,但我不确定在此之前该怎么做。


2) 网址为“file://localhost/Users/mingyeow/Desktop/index.html”

如何手动设置根 url 以使用 localhost:3000/我的网址?

【问题讨论】:

    标签: backbone.js trigger.io backbone-routing


    【解决方案1】:
    // define router
    var Router = Backbone.Router.extend({
      routes : {
        'index' : 'indexAction',
        '*default' : '_defaultAction'
      },
      indexAction : function() {
        // this will be executed when user navigate to #index
      },
      _defaultAction : function() {
        // this will be executed when user navigate anywhere else (#XXX)
      }
    });
    
    // on document ready
    $(function() {
      // initialize router
      new Router();
      // and start history
      Backbone.history.start();
    });
    

    您可以导航this way

    或者点击链接:<a href="#index"">Index route</a>


    您可以使用 python 服务器。要启动它,请在终端中输入:

    $ python -m SimpleHTTPServer
    

    然后检查http://localhost:8000

    【讨论】:

      【解决方案2】:

      1) 要触发路由更改,您只需通过 href 或 JavaScript(如 window.location)导航到页面。阅读Backbone Routes,但基本上你需要为每个“页面”编写一个函数。每个函数都应该负责呈现页面。

      2) 这应该很简单。您需要一个本地 Web 服务器。我最近开始做的只是拥有一个简单的 Node 服务器。 Node 非常易于安装,值得一试。下载静态 Web 服务器,例如 this one I made。要使用它,只需将您的主干应用程序放在名为“public”的目录中,然后在 node.js 中运行 server.js。 如果您不想这样做,您可以运行一个简单的 LAMP/WAMP/MAMP 安装并设置 Apache Web 服务器的根目录。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 2021-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多