gpt4 book ai didi

Meteor.js - 如何从客户端观察 Changes()

转载 作者:行者123 更新时间:2023-12-01 12:35:58 24 4
gpt4 key购买 nike

我是 Meteor 的新手。我正在尝试使用 Meteor 创建概念证明,其中对 Mongo oplog 的更新显示在浏览器屏幕上。

目前,我正在努力使 simple-todos 适应这个目的。我将服务器日志更新记录到终端,但不知道如何将其传输到客户端浏览器屏幕?

if(Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);

Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});

Template.hello.events({
'click button': function () {
// increment the counter when button is clicked
Session.set('counter', Session.get('counter') + 1);
}
});
}

if(Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
var Test = new Mongo.Collection('test');
var query = Test.find({});
var init = true;
query.observeChanges({
added: function(id, fields) {
if(!init)
console.log('doc inserted');
},
changed: function(id, fields) {
console.log('doc updated');
},
removed: function() {
console.log('doc removed');
}
});
init = false;
});
}

最佳答案

为服务器和客户端定义集合:

//collection Test for client and server
var Test = new Mongo.Collection('test');
if (Meteor.isClient) {
//subscribe for collection test
Meteor.subscribe('test');
Template.hello.helpers({
test: function() {
var query = Test.find();
query.observeChanges({
added: function(id, fields) {
console.log('doc inserted');
},
changed: function(id, fields) {
console.log('doc updated');
},
removed: function() {
console.log('doc removed');
}
});
return query;
}
});
}

if (Meteor.isServer) {
Meteor.publish('test', function() {
return Test.find();
});
}

对于更复杂的应用程序,您应该将应用程序结构化为多个目录和文件。在 Meteor docs 中阅读相关信息.

关于Meteor.js - 如何从客户端观察 Changes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29757449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com