如何在没有流星数据库的情况下编写一个简单的聊天.js并做出反应.js



我想在meteor.js上写一个简单的聊天,因此我不想将数据存储在database中。但是我从来没有找到如何在没有database的情况下制作应用程序.

这是我可以想象的代码示例。服务器代码:

export let ws = [{_id:'1', text:'test1'}, {_id:'2', text:'test2'}];
Meteor.publish('ws', function wsPub() { return ws; });
let ctr = 3;
Meteor.methods({
    'addMsg'(text) {  ws.push({_id:ctr+1, text:text});  }
});

和客户端代码:

import {ws} from '../api/model.js';
class Rtc extends Component {
  constructor(props) {
    super(props);
  }
  addMsg(e){
    e.preventDefault();
    Meteor.call('addMsg', this.refs.input.value);
  }
  render() {
    return (
      <div>
         {this.props.ws.map((item, i)=>{ 
           return(<span key={i._id}>{item.text}</span>); 
         })}
         <input type="text" ref="input" />
         <input type="submit" value="submit" onClick={this.addMsg.bind(this)}/>
       </div>
    );
  }
}
export default createContainer( () => {
  Meteor.subscribe('ws');
  return { ws: ws };
}, Rtc);

但我不明白我写的不是这样createContainer

UPD:我更新了服务器代码,但仍然 websocket 不起作用:

Meteor.publish('ws', function wsPub() {
  let self = this;
  ws.forEach( (msg)=> {
    self.added( "msg", msg._id, msg.text );
  });
  self.ready();
  // return ws;
});
如果要

控制通过发布发送的内容,请获取对"发布实例"(实际上是具有特定订阅的特定客户端(的引用,并使用其add/change/remove命令:

let messages = [];
let clients = [];
Meteor.publish('ws', function() {
    clients.push(this);
    _.each(messages, (message) => {this.added('msg', message._id, message);});
    this.ready();
});
Meteor.methods({
    addMsg(text) {
        let newMessage = {_id: Meteor.uuid(), text: text};
        messages.push(newMessage);
        _.each(clients, (client) => {client.added('msg', newMessage._id, newMessage);});
    }
});

关于您在更新中编写的代码:您正在发送一个string,其中函数added需要一个文档(object(。此外,与上面的此示例不同,您不会在ws(消息数组(更改时告诉客户端。

我建议将这些内容重命名为更冗长和清晰:)

你认为什么行不通。因为Meteor.publish返回游标到Collections Collectionarray。根据官方文件:

发布函数可以返回 Collection.Cursor,在这种情况下,Meteor 会将光标的文档发布到每个订阅的客户端。您还可以返回 Collection.Cursors 数组,在这种情况下,Meteor 将发布所有游标。

同样,当您订阅发布时,它会将数据(作为光标到与发布相同的集合(本地存储在 MiniMongo 中。因此,在 Meteor 中使用 pub-sub 进行没有数据库的聊天在技术上是不可能的。

最新更新