Backbone Require.js单页应用程序不工作,除非刷新

时间:2014-04-21 23:35:16

标签: backbone.js requirejs

我正在使用require.js和单页backbone.js应用程序。在利用require.js之前,我可以单击链接,页面内容将按预期加载而不刷新,但现在,除非我刷新页面,否则它将不会加载。

这是我的索引页面:

<body>
<header></header>
<nav>
    <a href="#/1">World</a>
    <a href="#/2">Business</a>
    <a href="#/3">Opinion</a>
    <a href="#/4">Sports</a>
    <a href="#/5">Fashion & Style</a>
    <a href="#/6">Video</a>
</nav>
<section id="container"></section>
<footer></footer>



<!-- Templates -->
<script type="text/template" id="featuredarticles">
    <h2>This is the main content</h2>
    <ul id="test"></ul>
 </script>

<script type="text/template" id="contentarticles">
    <h2>This is a page</h2>
    <ul id="test2"></ul>
</script>

<!-- Require.js reference -->
<script src="/js/libs/require.js" data-main="/js/app.js"></script>

这是我的app.js页面,其中包含require.js配置:

require.config({
paths: {
    jquery: "libs/jquery-2.1.0.min",
    underscore: "libs/underscore-min",
    backbone: "libs/backbone-min",
},
shim: {
    underscore: {
        exports: "_"
    },
    backbone: {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
    },
}
});

require(['routers/siteRouter'], function(router) {
 new router;
});

这是我的路由器:

define(['underscore', 'backbone', 'views/featuredArticlesView', 'views/contentArticlesView'], function (_, Backbone, featuredArticlesView, contentArticlesView) {

var siteRouter = Backbone.Router.extend({
    routes: {
        '': 'featuredArticlesView',
        '1': 'contentArticlesView',
        '2': 'contentArticlesView',
        '3': 'contentArticlesView',
        '4': 'contentArticlesView',
        '5': 'contentArticlesView',
        '6': 'contentArticlesView'
    }
});
var router = new siteRouter();
router.on('route:featuredArticlesView', function () {
    new featuredArticlesView();
});
router.on('route:contentArticlesView', function () {
    new contentArticlesView();
});

Backbone.history.start();

return siteRouter;
});

1 个答案:

答案 0 :(得分:0)

修正了它。我的路由器中有两个变量,只返回&#34; siteRouter&#34;。将这些包装在函数中解决了它。

define(['underscore', 'backbone', 'views/featuredArticlesView', 'views/contentArticlesView'], function (_, Backbone, featuredArticlesView, contentArticlesView) {

function routing() {

    var siteRouter = Backbone.Router.extend({
        routes: {
            '': 'featuredArticlesView',
            '1': 'contentArticlesView',
            '2': 'contentArticlesView',
            '3': 'contentArticlesView',
            '4': 'contentArticlesView',
            '5': 'contentArticlesView',
            '6': 'contentArticlesView'
        }
    });
    var router = new siteRouter();
    router.on('route:featuredArticlesView', function () {
        new featuredArticlesView();
    });
    router.on('route:contentArticlesView', function () {
        new contentArticlesView();
    });

    Backbone.history.start();
}
return routing;
});