如何覆盖 coffeescript 子类中的 Backbone.Router.execute 函数



我有一个类,它使用coffeescript中的extends关键字扩展了Backbone.Router。如何在我的类中重写 Backbone.Router.execute 方法?

我尝试使用相同的方法签名在我的子类中添加一个执行,但它仍然调用父类方法而不是我的自定义方法。

jQuery ->
  class MyRouter extends Backbone.Router
    routes:
      "path/:id"          : "myFunction"
    execute: (callback, args, name) ->
      console.log('hello')
      console.log(args)
      # do stuff
      args.push(parseQueryString(args.pop()));
      if callback
         callback.apply(@, args);
   myFunction: (id) ->
     # do stuff

我想在调用 myFunction 之前对 args 添加一些检查,但不知何故无法覆盖执行方法。我在这里做错了什么?

看起来你根本无法混合 Backbone 的对象和 ES6 类。

这是一篇非常详细解释它的帖子。

事实证明,ES6 类不支持将属性直接添加到类实例,仅支持函数/方法。当您了解实际发生的事情时,这是有道理的。使用 JavaScript 继承,属性通常意味着在创建实例时在实例上设置,而方法在原型对象上设置并在每个实例之间共享。如果属性直接添加到原型中,它们也将在每个实例之间共享,如果属性是具有可变状态的对象(如数组(,则会产生问题。


你将不得不坚持使用Object.extends()的骨干方式。下面是 coffeescript 中代码的示例:

MyRouter = Backbone.Router.extend        
    routes:
      "path/:id"          : "myFunction"
    execute: (callback, args, name) ->
      console.log('hello')
      console.log(args)
      # do stuff
      args.push(parseQueryString(args.pop()));
      if callback
         callback.apply(@, args);
   myFunction: (id) ->
     # do stuff

最新更新