浏览代码

A small chat experiment using meteor.

Lucas Stadler 12 年之前
父节点
当前提交
8adc1fc302
共有 2 个文件被更改,包括 65 次插入0 次删除
  1. 29 0
      js/helo/helo.html
  2. 36 0
      js/helo/helo.js

+ 29 - 0
js/helo/helo.html

@ -0,0 +1,29 @@
1
<head>
2
  <title>helo</title>
3
</head>
4
5
<body>
6
  {{#if user_name}}
7
    {{> chat}}
8
  {{/if}}
9
  
10
  {{#unless user_name}}
11
    {{> login}}
12
  {{/unless}}
13
</body>
14
15
<template name="chat">
16
  <div id="chat">
17
    {{#each messages}}
18
      <div class="message">
19
        <time>{{time timestamp}}</time>
20
        <strong>{{name}}</strong>: {{text}}
21
      </div>
22
    {{/each}}
23
  </div>
24
  <input type="text" id="message" placeholder="say something" />
25
</template>
26
27
<template name="login">
28
  <input type="text" id="user_name" placeholder="your name" />
29
</template>

+ 36 - 0
js/helo/helo.js

@ -0,0 +1,36 @@
1
Messages = new Meteor.Collection('messages');
2
3
if (Meteor.isClient) {
4
  Template.login.events({
5
    'keydown input#user_name' : function(ev) {
6
      if (ev.keyCode == 13) {
7
        Session.set('user_name', ev.target.value);
8
      }
9
    }
10
  });
11
12
  Handlebars.registerHelper('user_name', function() {
13
    return Session.get('user_name');
14
  });
15
16
  Template.chat.messages = function() {
17
    return Messages.find({}, {sort: {timestamp: 1}});
18
  }
19
20
  Handlebars.registerHelper('time', function(timestamp) {
21
    var date = new Date(timestamp);
22
    var pad = function(n) { return n < 10 ? "0" + n : n.toString() };
23
    return pad(date.getHours()) + ":" + pad(date.getMinutes());
24
  });
25
26
  Template.chat.events({
27
    'keydown input#message' : function(ev) {
28
      if (ev.keyCode == 13 && ev.target.value.length > 0) {
29
        Messages.insert({name: Session.get('user_name'),
30
                         text: ev.target.value,
31
                         timestamp: new Date().getTime()});
32
        ev.target.value = "";
33
      }
34
    }
35
  });
36
}