Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Router event binding not firing

Tags:

backbone.js

I'm trying to follow Organizing your application using Modules (require.js I'm struggling to understand how routing works.

I cannot get simple binding to work for index:

// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  'views/projects/list'
], function ($, _, Backbone, ProjectListView) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            '': 'index'
        }
    });

    var initialize = function () {
        var app_router = new AppRouter();

        app_router.on('index', function () {
            alert("index"); // this never gets called
        });

        Backbone.history.start();

        return app_router;
    };
    return {
        initialize: initialize
    };
});

When page is loaded nothing happens. This however works:

// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  'views/projects/list'
], function ($, _, Backbone, ProjectListView) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            // Define some URL routes
            '': 'index'
        },
        index: function() { alert("works"); }
    });

    var initialize = function () {
        var app_router = new AppRouter;

        Backbone.history.start();

        return app_router;
    };
    return {
        initialize: initialize
    };
});

Am I missing something?

like image 570
Fdr Avatar asked Nov 27 '12 11:11

Fdr


1 Answers

Ok, so this is how it's done:


    var initialize = function () {
        var app_router = new AppRouter();

        app_router.on("route:index", function () {
            alert("hello world");
        });

        Backbone.history.start();

        return app_router;
    };
like image 189
Fdr Avatar answered Oct 13 '22 15:10

Fdr