MeteorのPub/Subを理解するためにできるだけ最小構成で書いてみた
HTML
<head> <title>pub/sub test</title> </head> <body> {{> tweets}} </body> <template name="tweets"> <div id="items-view"> <div id="new-tweet-box"> <input type="text" id="new-tweet" placeholder="New item" /> </div> <ul id="item-list"> {{#each tweets}} {{> tweet_item}} {{/each}} </ul> </div> </template> <template name="tweet_item"> <li class="tweet {{done_class}}"> <div class="tweet-text">{{text}} : {{timestamp}}</div> </li> </template>
// Tweets -- {text: String, // timestamp: Number} Tweets = new Meteor.Collection("tweets"); if (Meteor.isClient) { // Always be subscribed to the todos for the selected list. Meteor.autosubscribe(function () { Meteor.subscribe('tweets'); }); Template.tweets.events = { 'keydown #new-tweet': function(e) { if(e.keyCode == 13) { console.log("Insert : " + text); var text = String(e.target.value || ""); if (text){ Tweets.insert({ text: text, timestamp: (new Date()).getTime() }); } e.target.value = ''; } } } Template.tweets.tweets = function () { return Tweets.find({}, {sort: {timestamp: 1}}); }; } if (Meteor.isServer) { Meteor.publish('tweets', function () { return Tweets.find({}, {sort: {timestamp: 1}}); }); }