如何将我的路由器绑定到我的方法-Backbonejs

How do I bind the my Router to my method - Backbonejs

本文关键字:我的 方法 -Backbonejs 绑定 我的路 路由器      更新时间:2023-12-19

我正在尝试将一个方法绑定到我的主干路由器。这是我的课:

define(function(require) {
  'use strict';
  var Backbone = require('backbone');
  var Header = require('views/header.view');
  var MainBody = require('views/main.body.view');
  var Router = Backbone.Router.extend({
    currentView: null,
    routes: {
      "about": "about"
    },
    initialize: function() {
      Backbone.on('location', this.test);
      debugger;
      _.bindAll(this, 'test');
    },
    about: function() {
      var header = new Header();
      $('#header').html(header.render().el);
    },
    test: function(data) {
      this.currentView.close();
    }
  });
  return Router;
});

在初始化块中,我试图将this绑定到test。当我调用test函数时,我的this仍然是Backbone,而不是当前类。我做错了什么?我该如何解决这个问题?

您在附加处理程序后绑定它。

initialize: function() {
    // `test` is bound with the wrong THIS
    Backbone.on('location', this.test);
    debugger;
    // Here you actually do the binding
    _.bindAll(this, 'test');
 },

只需交换订单,看看这是否解决了您的问题。

我认为在上调用Backbone.on时需要第三个参数

要在调用回调时为此提供上下文值,请传递可选的第三个参数:model.on('change', this.render, this)

像这个Backbone.on('location', this.test, this);