【问题标题】:Unable to get Backbone.js route handlers to fire on matching route无法让 Backbone.js 路由处理程序在匹配的路由上触发
【发布时间】:2013-10-10 22:47:04
【问题描述】:

我正在关注Organizing Backbone Using Modules tutorial,除了在撰写本文后我必须进行一些调整以适应对依赖项的更改之外,我无法让我的 .on() 事件触发当路由匹配时。

如果您查看索引路由器,您会看到一个警报和一个 console.log()。页面加载时也不会触发。也没有js错误。

任何帮助将不胜感激。

router.js

define([
  'jquery', 
  'underscore', 
  'backbone',
  'views/index',
  'views/ideas'
], function($, _, Backbone, IndexView, IdeasView) {

  var AppRouter = Backbone.Router.extend({
    '': 'index',
    '/ideas': 'showIdeas',
    '*actions': 'defaultAction'
  });

  var initialize = function() {

    console.log('this works so i know initialize() is being called');

    var app_router = new AppRouter;

    // not firing
    app_router.on('route:index', function() {
      alert('hi');
      console.log('hi');
      // var index_view = new IndexView();
      // index_view.render();
    });

    // not firing
    app_router.on('route:showIdeas', function() {
      console.log('showIdeas');
      var ideas_view = new IdeasView();
    });

    //not firing
    app_router.on('route:defaultAction', function(actions) {
      console.log('No route:', actions);
    });

    if (!Backbone.history.started ) {
      Backbone.history.start();
      console.log( "Route is " + Backbone.history.fragment );
    }
  };

  return {
    initialize: initialize
  };
});

【问题讨论】:

  • 什么是没有触发您的路由之一的 url 示例?
  • 怎么样/或者更具体地说,0.0.0.0:3000

标签: javascript backbone.js


【解决方案1】:

确保将您的实际路由放在路由器定义上的路由哈希中:

var AppRouter = Backbone.Router.extend({
    routes: {
        '': 'index',
        '/ideas': 'showIdeas',
        '*actions': 'defaultAction'
    }
});

我还要补充一点,我更喜欢将路由的回调放在路由器定义中(这只是一个偏好):

var AppRouter = Backbone.Router.extend({
    routes: {
        '': 'index',
        '/ideas': 'showIdeas',
        '*actions': 'defaultAction'
    },

    index: function () {
        // function body here
    },

    showIdeas: function () {
        // function body here
    },

    defaultAction: function () {
        // function body here
    }
});  

这不是必需的,但对我来说它更容易阅读并了解发生了什么。

【讨论】:

  • 啊,完全错过了。不错的收获。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2017-05-04
相关资源
最近更新 更多