在初始化中回调之前不会在骨干网中渲染路由

时间:2013-01-19 20:47:24

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

对不起,标题有点令人困惑。

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

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
        }});
    }
});

我遇到的问题是我需要将用户传递给视图,所以我需要每个渲染只在成功回调在initialize内部运行时运行。基本上我不希望初始化完成,直到调用回调。我无法弄清楚如何实现这一目标。

由于

1 个答案:

答案 0 :(得分:2)

默认情况下,

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;
}