Skip to content

Commit b00f216

Browse files
committed
fix issues in chat
1 parent fd900c0 commit b00f216

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

chat/index.coffee

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,11 @@ app.component require('d-before-unload')
99
NUM_USER_IMAGES = 10
1010
ONE_DAY = 1000 * 60 * 60 * 24
1111

12-
app.on 'model', (model) ->
13-
# Defined by name so that it can be re-initialized on the client
14-
model.fn 'pluckUserIds', (items = {}, additional) ->
15-
ids = {}
16-
ids[additional] = true if additional
17-
for key, item of items
18-
ids[item.userId] = true if item?.userId
19-
return Object.keys ids
12+
getUserPaths = (messages = {}, userId) ->
13+
paths = ["users.#{userId}"]
14+
for id, message of messages
15+
paths.push "users.#{message.userId}"
16+
return paths
2017

2118
app.get '/:room?', (page, model, {room}, next) ->
2219
# Only handle URLs that use alphanumberic characters, underscores, and dashes
@@ -30,24 +27,24 @@ app.get '/:room?', (page, model, {room}, next) ->
3027
messagesQuery.subscribe (err) ->
3128
return next err if err
3229

33-
# Subscribe to all displayed userIds, including the userIds associated
34-
# with each message and the current session's userId
35-
model.start '_page.userIds', 'messages', '_session.userId', 'pluckUserIds'
36-
usersQuery = model.query 'users', '_page.userIds'
37-
usersQuery.subscribe (err) ->
30+
messages = model.get 'messages'
31+
userId = model.get '_session.userId'
32+
paths = getUserPaths messages, userId
33+
model.subscribe paths, (err) ->
3834
return next err if err
3935

40-
user = model.at 'users.' + model.get('_session.userId')
36+
user = model.at "users.#{userId}"
4137
# Render page if the user already exists
4238
return page.render() if user.get()
4339

4440
# Otherwise, initialize user and render
4541
userCount = model.at 'chat.userCount'
4642
userCount.fetch (err) ->
4743
return next err if err
44+
userCount.create(0) unless userCount.get()?
4845
userCount.increment (err) ->
4946
return next err if err
50-
user.set
47+
user.create
5148
name: 'User ' + userCount.get()
5249
picClass: 'pic' + (userCount.get() % NUM_USER_IMAGES)
5350
page.render()
@@ -75,6 +72,13 @@ app.proto.create = (model) ->
7572
return unless @atBottom
7673
@container.scrollTop = @list.offsetHeight
7774

75+
# Subscribe to new users as messages are loaded
76+
model.on 'load', 'messages.*', =>
77+
messages = model.get 'messages'
78+
userId = model.get '_session.userId'
79+
paths = getUserPaths messages, userId
80+
model.subscribe paths
81+
7882
app.proto.onScroll = ->
7983
# Update whether the user scrolled up from the bottom or not
8084
bottom = @list.offsetHeight

0 commit comments

Comments
 (0)