"context" Firebase.on 的参数无效

"context" argument of Firebase.on is not working

"context" 是 Firebase.on

的第 4 个参数
on(eventType, callback, [cancelCallback], [context])

https://www.firebase.com/docs/web/api/query/on.html

context Object *optional

If provided, this object will be used as this when calling your callback.

不过好像不行。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>firebase sample</title>

  <script src="bower_components/firebase/firebase-debug.js"></script>
</head>
<body>

  <script>
    (function () {
      var listener = {
        onChildAdded: function (snapshot) {
          console.log(this);
        }
      };
      console.log(listener);

      var ref = new Firebase("https://<YOUR_FIREBASE_APP>.firebaseio.com");
      ref.on("child_added", listener.onChildAdded, null, listener);
    })();
  </script>
</body>
</html>

预期:对象 ({ onChildAdded: function... })

结果:Window(浏览器全局对象)

image.png

所以我用bind方法解决了这个问题

ref.on("child_added", listener.onChildAdded.bind(listener));

这个问题是错误还是规范?

我认为问题是如果第 3 个参数为 null 它没有考虑第 4 个参数所以尝试传递一个空函数作为第 3 个参数

ref.on("child_added", listener.onChildAdded, function(){}, listener);

实际上根据源代码,可选的 cancel 回调应该被省略,而不是提供 null/undefined 值。这在文档中可能并不明显,但 cancel 是可选的