0

我的 Backbone 应用程序的第一个状态是从服务器呈现的。我不需要在页面加载时触发路由器,因为我正在引导我的模型:

我启动应用程序:

    window.App = {
        init:function(root){
            this.root = root;
            this.router = new AppRouter();
            Backbone.history.start({pushState:true, silent:true});
        }
    }

路线[s]:

var AppRouter = Backbone.Router.extend({
        routes : {
            "" : "index",
            "profile/:id" : "profile",
        },
        profile: function(id){
            var user = new App.Models.User({id: id});
            var view = (new App.Views.Profile({model:user})).render().el

            App.root.empty().append(view)
        }

看法:

    App.Views.Profile = Backbone.View.extend({
        events:{
            "click #toggle" : "toggleTab"
        },
        initialize:function(opts){
            this.model.on('sync', this.render, this);
            this.model.fetch();
        },
        template: Handlebars.templates['profile.hbs'],
        render: function(){
            this.$el.html(this.template());
            return this;
        },
        toggleTab:function(){...}

我正在传递silent: true给 Backbone.history,因此不会触发初始路由,因此click不会绑定事件。这发生在不触发路由器的事件上。我真的不想在页面加载和重新渲染/获取时触发路由器。navigate在这种情况下,ing 不是一种选择。

在这种情况下,如何绑定此类事件?


更新/澄清

出于 SEO 的原因,服务器呈现 html 意味着我已经拥有 html 和那里的数据(我真的不需要empty()、重新呈现、触发或获取任何东西。我在服务器和客户端中都使用把手。我知道这里的问题是“初始页面”不是“Backbone.View”,所以它没有得到事件绑定。我可以很容易地触发路由器和/或通过生成视图来替换内容,但是当我已经拥有了我不想那样做的一切。我应该只引导模型并重新渲染 html 吗?这有最佳实践吗?

4

0 回答 0