Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Meteor in-memory-collection example chat
<head>
<title>example-chat</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<p>You've pressed the button {{counter}} times.</p>
{{#each chats}}
Chat ID: {{ _id }}
{{#each messages}}
<p>Melding: {{msg}} Avsender: {{sender}}</p>
{{/each}}
<input type="text" id="anonmessage" data-chat-id="{{_id}}" />
<button>Send</button>
{{/each}}
</template>
if (Meteor.isClient) {
ChatsInMemory = new Mongo.Collection('ChatsInMemory');
Meteor.subscribe('ChatsInMemory');
Template.hello.helpers({
chats: function () {
return ChatsInMemory.find({}).fetch();
}
});
Template.hello.events({
'click button': function (event, template) {
var inputElement = document.getElementById('anonmessage');
console.log("inputelement:", inputElement.value);
Meteor.call('sendMessage', { chatId: this._id, message: inputElement.value });
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
Meteor.methods({
sendMessage: function (options) {
ChatsInMemory.upsert(
{ _id: options.chatId },
{
$push: { messages: { msg: options.message, sender: "Du" } }
},
function (error, id) {
if (error) {
throw new Meteor.Error(500, "Server error, please try again.");
}
console.log('ID from inserting ChatsInMemory', id);
console.log(ChatsInMemory.find({}).fetch());
});
}
})
ChatsInMemory = new Mongo.Collection(null);
ChatsInDB = new Mongo.Collection('ChatsInDB');
ChatsInMemory.insert({ messages: [{ msg: 'hei', sender: 'Du'}, { msg: 'initiell', sender: 'Red Cross'} ]});
ChatsInDB.insert({ messages: [{ msg: 'heiDB', sender: 'DuDB'}, { msg: 'initiellDB', sender: 'Red CrossDB'} ]});
Meteor.publish("ChatsInMemory", function () {
var self = this;
var id = Random.id();
var handle = ChatsInMemory.find({})
.observeChanges({
added: function (id, fields) {
console.log("We are adding to ChatsInMemory in publish");
self.added("ChatsInMemory", id, { messages: fields.messages });
},
changed: function (id, fields) {
self.changed("ChatsInMemory", id, { messages: fields.messages });
},
removed: function (id) {
self.removed("ChatsInMemory", id);
}
});
self.ready();
self.onStop(function () {
handle.stop();
});
});
Owner

makrem025 commented Dec 7, 2015

Publish.js should recide in server-folder in a Meteor-application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment