【问题标题】:not render routes in backbone until callback in initialize在初始化回调之前不渲染主干中的路由
【发布时间】:2013-01-20 08:02:54
【问题描述】:

抱歉,标题有点混乱。

我的骨干路由器具有以下结构:

var AppRouter = Backbone.Router.extend({
    routes: {
      'notes': 'showNotes',
      'news': 'showNews'
    },
    showNews: function() {
        // make view object and render
    },
    showNotes: function() {
        // make view object and render
    },
    initialize: function() {
        this.user.fetch({success: function(){
            // callback function
        }});
    }
});

我遇到的问题是我需要将用户传递到视图中,因此我需要每个渲染仅在成功回调在初始化内部运行时才运行。基本上我不想在调用回调之前完成初始化。我不知道我怎么能做到这一点。

谢谢

【问题讨论】:

    标签: javascript model-view-controller backbone.js


    【解决方案1】:

    Router#initialize,默认情况下是一个空函数。在它运行时,路线已经移交给History,您可能已经通过任何“干净”的方式来阻止它们。

    如果您真的需要确保在路由器开始渲染之前获取您的用户,您可以通过在历史记录开始之前获取user 来实现这一点,一些像这样:

      // in some initializer:
      user.fetch({success: function() {
        var router = new AppRouter({user: user});
        Backbone.history.start();
      }});
    
      // and your router:
      initialize: function(options) {
        if (options) this.user = options.user;
      }
    

    但让视图响应用户被获取而不是确保预先加载它也可能是有意义的。在用户加载之前,视图可能不会渲染任何内容,或者它可能会显示“正在加载”的图形等。在这种情况下,您只需:

    // in your router
    showNotes: function() {
      // note sure how you're storing your views, but for example:
      this.currentView = new ShowNotesView({model: this.user}).render();
    },
    
    initialize: function() {
      this.user.fetch();
    }
    
    // and in the view
    initialize: function() {
      this.model.on('sync', this.render.bind(this));
    },
    
    render: function() {
      // note that `hasBeenSynced` is a made up property.  Fill it in with something
      // that indicates the model has been fetched successfully.  Alternatively you
      // might do this in the template.  Lot of flexibility here.
      if (this.model.hasBeenSynced) {
        // render the model
      } else {
        // show nothing, a loading template, etc
      }
      return this;
    }
    

    【讨论】:

    • 这是完美的。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多