从枪中获取流数据

Getting streaming data from gun

on() 应该从路径或键 1 流式传输数据。但是当我 put 数据在我的路径上时,我没有看到更新的流。

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on();
myData.put({hello:'world'});

.on() 是一个 异步 函数,因此您需要将代码更新为如下所示:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on(function(data){
    console.log("update:", data);
});
myData.put({hello:'world'});

希望对您有所帮助!


如果您是编程新手,上面代码中的 "anonymous functions"(通常称为回调)可能会有些混乱。上面的代码也可以重写为这样,它具有完全相同的行为:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');

var cb = function(data){
    console.log("update:", data);
};

myData.on(cb);

myData.put({hello:'world'});

为了调试目的,还有一个.val()方便的功能,它会自动为您记录数据:

var myData = Gun('https://gunjs.herokuapp.com/gun')
             .get('example/demo/set');
myData.on().val()
myData.put({hello:'world'});

但是,它仅用于一次性目的,而不是用于流式传输。请注意,您可以传递 .val(function(data){}) 一个回调,它将覆盖默认的便利记录器。

更新:因为使用val()的Gun v0.391也需要回调。不再提供自动记录。