简体   繁体   English

Backbone.js和router.navigate

[英]Backbone.js and router.navigate

I'm trying to improve the navigation of my little backbone application. 我正在尝试改善我的小骨干网应用程序的导航。 Right now I just have some simple navigation using html links that use to #path/to/page in the href element. 现在,我只是使用html链接进行了一些简单的导航,这些链接用于href元素中的#path / to / page。

What I'm running into is when I click on one of these and then click the back button, the page doesn't refresh properly, and the HTML content doesn't change. 我遇到的是,当我单击其中之一,然后单击“后退”按钮时,页面无法正确刷新,并且HTML内容没有更改。 So I'm trying to incorporate the navigate functionality into my code. 因此,我试图将导航功能合并到我的代码中。

The issue I'm running into is that I can't find an example that matches the code layout I'm currently using, and I don't understand how backbone works enough to adapt the things I find into something useful. 我遇到的问题是,找不到与我当前使用的代码布局相匹配的示例,而且我不了解主干如何充分发挥作用以将我发现的内容改编成有用的东西。

Here's what I've got: 这是我得到的:

app.js - called from the index.html file app.js-从index.html文件调用

require.config({

    baseUrl: 'js/lib',

    paths: {
        app: '../app',
        tpl: '../tpl',
        bootstrap: 'bootstrap/js/',

    },

    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        }
    }
});

require([
    'jquery', 
    'backbone', 
    'app/router',
], function ($, Backbone, Router) {
    var router = new Router();
    Backbone.history.start();
});

app/router.js - instantiated in app.js app / router.js-在app.js中实例化

define(function (require) {

    "use strict";

    var $           = require('jquery'),
        Backbone    = require('backbone'),
        WindowView   = require('app/views/Window'),

        breadcrumbs = {"Home": ""},
        $body = "",
        $content = "",
        windowView = "";

    return Backbone.Router.extend({

        initialize: function () {
            require([], function () {
                $body = $('body');
                windowView = new WindowView({el: $body}).render();
                $content = $("#content", windowView.el);
            });
        },

        routes: {
            ''                                                : 'home',
            'profile/login(/)'                                : 'candidateProfileLogin',
            'profile/manage(/)'                               : 'candidateProfileLogin',
            'profile/manage/:id(/)'                           : 'candidateProfileHome',
            'profile/manage/:id/questionnaire/:page(/)'       : 'candidateProfileQuestionnaire',
            'profile/manage/:id/:section(/)'                  : 'candidateProfileSection',
        },

        home: function (){
        },

        candidateProfileLogin: function () {
            require(['app/views/CandidateLogin'], function (CandidateLoginView) {
                console.log(Backbone.history.fragment);
                var view = new CandidateLoginView({el: $content});
                view.render();
            });
        },

        candidateProfileHome: function (id) {
            require(["app/views/Candidate", "app/models/candidate"], function (CandidateView, models) {
                var candidate = new models.Candidate({id: id});
                candidate.fetch({
                    success: function (data) {
                        var view = new CandidateView({model: data, el: $content});
                        view.render();
                    },
                    error: function (data) {
                        var view = new CandidateView({model: data, el: $content});
                        view.render();
                    }
                });
            });
        },

        candidateProfileSection: function (id, section) {
            require(["app/views/Candidate", "app/models/candidate"], function (CandidateView, models) {

                var candidate = new models.Candidate({id: id});
                candidate.fetch({
                    success: function (data) {
                        var view = new CandidateView({model: data, el: $content});
                        view.render(section);
                    },
                    error: function (data) {
                        //Output the data to the console. Let the template take care of the error pages
                        console.log(data);
                        var view = new CandidateView({model: data, el: $content});
                        view.render();
                    }
                });
            });
        },

        candidateProfileQuestionnaire: function (id, page) {
            require(["app/views/Candidate", "app/models/candidate"], function (CandidateView, models) {
                var candidate = new models.Candidate({id: id});
                candidate.fetch({
                    success: function (data) {
                        var view = new CandidateView({model: data, el: $content});
                        view.render(page);
                    },
                    error: function (data) {
                        //Output the data to the console. Let the template take care of the error pages
                        console.log(data);
                        var view = new CandidateView({model: data, el: $content});
                        view.render();
                    }
                });
            });
        },
    });
});

app/views/Candidate.js - My view I'm trying to process the clicks app / views / Candidate.js-我的视图我正在尝试处理点击

define(function (require) {

    "use strict";

    var $                     = require('jquery'),
        _                     = require('underscore'),
        Backbone              = require('backbone'),
        tpl                   = require('text!tpl/Candidate.html'),
        template              = _.template(tpl),

        CandidateErrorView    = require('app/views/CandidateError'),
        errtpl                = require('text!tpl/CandidateError.html'),
        errTemplate           = _.template(errtpl);

    return Backbone.View.extend({

        events: {
            'submit #voters-guide-personalInfo': 'savePersonalInfo',
            'submit #voters-guide-essay'       : 'saveEssay',
            'submit #voters-guide-survey'      : 'saveSurvey',
            'submit #voters-guide-endorsements': 'saveEndorsements',
            'submit #voters-guide-photo'       : 'savePhoto',

            'click #table-of-contents a' : 'navTOC',
        },

        savePersonalInfo: function (event) {
            console.log(event);
        },

        saveEssay: function (event) {
            console.log(event);
        },

        saveSurvey: function (event) {
            console.log(event);
        },

        saveEndorsements: function (event) {
            console.log(event);
        },

        savePhoto: function(event) {
            console.log(event);
        },

        navTOC: function (event) {
            console.log(event.target);
            var id   = $(event.target).data('candidate-id');
            var path = $(event.target).data('path');
            //router.navigate("profile/manage/" + id + "/" + path, {trigger: true});
        },

        render: function (page) {
            //Check to see if we have any errors
            if (!this.model.get('error')) {
                var dataToSend = {candidate: this.model.attributes};

                switch(page) {
                    case 'personalInfo':
                        template = _.template(require('text!tpl/Candidate-personalInfo.html'));
                    break;

                    case 'essay':
                        template = _.template(require('text!tpl/Candidate-essay.html'));
                    break;

                    case 'survey':
                        template = _.template(require('text!tpl/Candidate-survey.html'));
                    break;

                    case 'endorsements':
                        template = _.template(require('text!tpl/Candidate-endorsements.html'));
                    break;

                    case 'photo':
                        template = _.template(require('text!tpl/Candidate-photo.html'));
                    break;

                    default:
                    break;
                }

                this.$el.html(template(dataToSend));
                return this;
            } else {
                this.$el.html(errTemplate({candidate: this.model.attributes}));
                return this;
            }
        }
    });
});

Now, in an attempt to stop the 'the page content doesn't reload when I hit the back button' issue, I've been looking into the navigate function that backbone has available (this: router.navigate(fragment, [options]); ). 现在,为了阻止“单击后退按钮时不重新加载页面内容”问题,我一直在研究骨干网可用的导航功能(这是: router.navigate(fragment, [options]); )。 There are lots of examples of how this is used, but none of them seem to have anything similar to the file setup that I'm using, so I'm not exactly sure how best to access this functionality from my view. 有很多使用此功能的示例,但似乎没有一个类似于我正在使用的文件设置,因此我不确定从我的角度来看如何最好地访问此功能。 If I include the router file in the view and instantiate a new version of it, the page breaks b/c it tries to run the initialize function again. 如果我在视图中包括路由器文件并实例化它的新版本,则该页面会中断b / c,它会尝试再次运行初始化函数。

I'm just really at a loss on how this is supposed to work. 我真的不知道该如何工作。

Can someone point me in the right direction? 有人可以指出我正确的方向吗?

Thanks! 谢谢! --Lisa --Lisa

PS If someone has any better ideas, I am all ears! 附言:如果有人有更好的主意,我会非常高兴!

You should have access to the Backbone object, which within it, has access to navigate around using the history.navigate function. 您应该可以访问其中的Backbone对象,该对象可以使用history.navigate函数进行导航。 If you call that passing in trigger: true you'll invoke the route. 如果您调用传递的trigger: true ,则将调用路由。 For instance: 例如:

Backbone.history.navigate("profile/manage", { trigger: true });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM