[Backbone.js]如何用backbone写一个仿网页版微信的webapp?
var Chat = Backbone.Model.extend({ idAttribute:'id', initialize:function(options){ var users = this.get('users'); this.set('users',new Users(users));//一个聊天会话里面,可能有一个或者多个用户,这个collection是用来保存这些用户数据的,如果用户有变动,直接在此通过colleciton来做处理 this.set('messages',new Messages([]));//一个聊天会话里有多条聊天数据,这个结构是保存聊天数据保存在正确的会话里 this.get('messages').on('add',function(msg){ var user_name = this.get('users').get(msg.get('user_id')).get('name'); console.log('a new msg comming:',msg.get('msg'),' from user:',user_name);//这个事件绑定了当新消息收到的时候,如果做事情处理,这里简单地console.log,事实上会重新new一个messageView来显示这个消息 },this); } }); //会话集合 var Chats = Backbone.Collection.extend({ model:Chat }); var User = Backbone.Model.extend({ }); var Users = Backbone.Collection.extend({ model:User }); var Message = Backbone.Model.extend({ }); var Messages = Backbone.Collection.extend({ model:Message }); var chat_source = [ {id:1,subject:'chat1',users:[1,2,3]}, {id:2,subject:'chat2',users:[1,2]}, {id:1,subject:'chat3',users:[2,3]} ]; var user_source = [ {id:1,name:'user1'}, {id:2,name:'user2'}, {id:3,name:'user3'}, ]; var chats = new Chats((function(chats,users){ _.each(chats,function(chat){ chat._users = []; _.each(chat.users,function(user_id){ _.each(users,function(user){ if(user.id === user_id){ chat._users.push(user); return; } }) }); delete chat.users; chat.users = chat._users; delete chat._users; }); return chats; })(chat_source,user_source)); var msg1 = {msg:'hello',user_id:2,chat_id:2}; var msg2 = {msg:'gogo',user_id:3,chat_id:1}; //当新消息数据来的时候,处理 function new_msg(msg){ var chat_id = msg.chat_id; var chat = chats.get(chat_id); var msg_model = new Message(msg); chat.get('messages').add(msg_model); } new_msg(msg1); //模拟新消息来 setTimeout(function(){ new_msg(msg2); },5000);