如何覆盖其 coffeescript 子 class 中的 Backbone.Router.execute 函数?

How do I override Backbone.Router.execute function in its coffeescript child class?

我有一个 class,它使用 coffeescript 中的 extends 关键字扩展 Backbone.Router。如何覆盖 class 中的 Backbone.Router.execute 方法?

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

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 添加一些检查,但不知何故无法覆盖 execute 方法。我在这里做错了什么?

看起来您根本无法混合使用 backbone 的对象和 ES6 类。

这里是post which explains it in great detail.

it turns out that ES6 classes don’t support adding properties directly to the class instance, only functions/methods. This makes sense when you understand what is actually happening. With JavaScript inheritance, properties are generally meant to be set on an instance when its created, while methods are set on the prototype object and shared between every instance. If properties are added to the prototype directly they will also get shared between every instance, creating problems if the property is an object with mutable state like an array


您将必须坚持使用 Object.extends() 的 backbone 方式。这是您在 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