PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/static/js/app.js

https://gitlab.com/fwh19890125/mychat
JavaScript | 410 lines | 271 code | 15 blank | 124 comment | 17 complexity | adc401396526ee1ac9803027adc6114d MD5 | raw file
  1. (function($){
  2. //alert(1);
  3. var socket = io.connect();
  4. socket.on('connect', function(){
  5. console.log('connected');
  6. });
  7. var User = Backbone.Model.extend({
  8. urlRoot: '/user',
  9. /*defaults:{
  10. id:"1",
  11. name:"ff"
  12. }*/
  13. });
  14. var Topic = Backbone.Model.extend({
  15. urlRoot: '/topic'
  16. });
  17. var Topics = Backbone.Collection.extend({
  18. url: '/topic',
  19. model: Topic,
  20. getTopic:function(topic_id){
  21. return this.where({"id":topic_id});
  22. }
  23. });
  24. var topics = new Topics;
  25. var Message = Backbone.Model.extend({
  26. urlRoot: '/message',
  27. sync: function(method, model, options) {
  28. if (method === 'create') {
  29. socket.emit('message', model.attributes);
  30. // 错误处理没做
  31. $('#comment').val('');
  32. } else {
  33. return Backbone.sync(method, model, options);
  34. };
  35. }
  36. });
  37. var Messages = Backbone.Collection.extend({
  38. url: '/message',
  39. model: Message
  40. });
  41. var LoginView = Backbone.View.extend({
  42. el:$(".login"),
  43. wrap:$(".login"),
  44. //user:$(".user"),
  45. //pass:$(".pass"),
  46. initialize:function(){},
  47. events:{
  48. "click #btnLogin":"onLoginClick",
  49. "click #btnRegister":"onRegisterClick"
  50. },
  51. show:function(){
  52. this.$el.show();
  53. },
  54. hide:function(){
  55. this.$el.hide();
  56. },
  57. onLoginClick:function(){
  58. //alert(this.user.val());
  59. var username_input = $('.user');
  60. var pwd_input = $('.pass');
  61. var u = new User({
  62. username: username_input.val(),
  63. password: pwd_input.val(),
  64. });
  65. u.save(null, {
  66. url: '/login',
  67. success: function(model, resp, options){
  68. g_user = resp;
  69. // 跳转到index
  70. appRouter.navigate('index', {trigger: true});
  71. },
  72. error: function(model, resp, options) {
  73. alert(resp.responseText);
  74. }
  75. });
  76. },
  77. onRegisterClick:function(){
  78. var username_input = $('#reg_user').val();
  79. var pwd_input = $('#reg_pass').val();
  80. //alert(username_input);
  81. var u = new User({
  82. username: username_input,
  83. password: pwd_input,
  84. password_repeat: pwd_input,
  85. });
  86. u.save(null, {
  87. success: function(model, resp, options){
  88. g_user = resp;
  89. // 跳转到index
  90. appRouter.navigate('index', {trigger: true});
  91. },
  92. error: function(model, resp, options) {
  93. alert(resp.responseText);
  94. }
  95. });
  96. }
  97. });
  98. var UserView = Backbone.View.extend({
  99. initialize:function(){},
  100. events:{}
  101. });
  102. var TopicView = Backbone.View.extend({
  103. tagName: "div",
  104. template: _.template($('#tpl_topic').html()),
  105. // 渲染列表页模板
  106. render: function() {
  107. $(this.el).html(this.template(this.model.toJSON()));
  108. $(this.el).addClass("u-topic");
  109. return this;
  110. }
  111. });
  112. var MessageView = Backbone.View.extend({
  113. tagName: "div",
  114. template: _.template($('#tpl_message').html()),
  115. // 渲染列表页模板
  116. render: function() {
  117. var _model=this.model.toJSON();
  118. var time=_model.created_time;
  119. time=time.substring(0,time.indexOf("."));
  120. _model.created_time= time;
  121. $(this.el).html(this.template(_model));
  122. $(this.el).addClass("f-cb");
  123. return this;
  124. }
  125. });
  126. var messages= new Messages;
  127. var AppView = Backbone.View.extend({
  128. el:".main",
  129. topic_section:$(".section_topic"),
  130. message_section:$(".section_message"),
  131. message_list:$(".m-msgList"),
  132. initialize:function(){
  133. topics.bind("add",this.addTopic);
  134. messages.bind("add",this.addMsg);
  135. this.message_pool = {};
  136. },
  137. events:{
  138. "click #btnAddTopic":"onClickAddTopic",
  139. "click #btnSendMsg":"onClickSendMsg"
  140. },
  141. showTopic:function(){
  142. topics.fetch();
  143. this.topic_section.show();
  144. this.message_section.hide();
  145. this.message_list.html('');
  146. },
  147. testAdd:function(){
  148. alert("text");
  149. },
  150. /*
  151. initMessage:function(topic_id){
  152. var messages = new Messages;
  153. messages.bind('add', this.addMsg);
  154. this.message_pool[topic_id] = messages;
  155. },*/
  156. showMessage:function(topic_id){
  157. //this.initMessage(topic_id);
  158. //var messages = this.message_pool[topic_id];
  159. socket.emit('topic', topic_id);
  160. // 监听message事件,添加对话到messages中
  161. socket.on('message', function(response) {
  162. messages.add(response);
  163. });
  164. messages.fetch({
  165. data: {topic_id: topic_id}
  166. });
  167. this.topic_section.hide();
  168. this.message_section.show();
  169. //var e= topics.where({"topic_id":topic_id});
  170. //var e=topics.getTopic(topic_id);
  171. //var t=e[0].get("title");
  172. //$("#topic_title").html(t);
  173. this.showMessageHead(topic_id);
  174. $('#msgTitle').attr('topic_id', topic_id);
  175. },
  176. showMessageHead: function(topic_id) {
  177. var topic = new Topic({id: topic_id});
  178. self = this;
  179. topic.fetch({
  180. success: function(resp, model, options){
  181. $("#topic_title").html(model.title);
  182. },
  183. error: function(model, resp, options) {
  184. alert(resp.responseText);
  185. }
  186. });
  187. },
  188. onClickAddTopic:function(){
  189. var topic_title=$("#topicTitle");
  190. if (topic_title.val() == '') {
  191. alert('主题不能为空!');
  192. return false
  193. }
  194. var topic = new Topic({
  195. title: topic_title.val(),
  196. });
  197. self = this;
  198. topic.save(null, {
  199. success: function(model, response, options){
  200. topics.add(response);
  201. topic_title.val('');
  202. },
  203. error: function(model, resp, options) {
  204. alert(resp.responseText);
  205. }
  206. });
  207. },
  208. addTopic:function(topic){
  209. var ele=new TopicView({model:topic});
  210. var view=ele.render().el;
  211. $(".m-topicList").append(ele.render().el);
  212. },
  213. onClickSendMsg:function(){
  214. var comment_box = $('#msgTitle')
  215. var content = comment_box.val();
  216. if (content == '') {
  217. alert('内容不能为空');
  218. return false;
  219. }
  220. var topic_id = comment_box.attr('topic_id');
  221. var message = new Message({
  222. content: content,
  223. topic_id: topic_id,
  224. });
  225. message.save(null,{
  226. success: function(){
  227. //messages.add()
  228. alert("send success");
  229. messages.reset();
  230. },
  231. error: function(){
  232. alert("消息发送失败");
  233. }
  234. }); // 依赖上面对sync的重载
  235. //var messages = this.message_pool[topic_id];
  236. var tmp={
  237. "user_id": g_user.id,
  238. "is_mine": true,
  239. "content": content,
  240. "topic_id": topic_id,
  241. "created_time": (new Date()).toLocaleString(),
  242. "user_name": g_user.username,
  243. "id": 10000
  244. }
  245. messages.add(tmp);
  246. comment_box.val('');
  247. },
  248. addMsg:function(message){
  249. var ele=new MessageView({model:message});
  250. var view=ele.render().el;
  251. $(".m-msgList").append(ele.render().el);
  252. },
  253. });
  254. var AppRouter = Backbone.Router.extend({
  255. routes: {
  256. "login": "login",
  257. "index": "index",
  258. "topic/:id" : "topic",
  259. },
  260. initialize: function(){
  261. // 初始化项目, 显示首页
  262. this.appView = new AppView();
  263. this.loginView = new LoginView();
  264. this.userView = new UserView();
  265. this.indexFlag = false;
  266. },
  267. login: function(){
  268. //alert("login");
  269. this.loginView.show();
  270. },
  271. index: function(){
  272. //alert("index");
  273. if (g_user && g_user.id != undefined) {
  274. this.appView.showTopic();
  275. //this.userView.show(g_user.username);
  276. this.loginView.hide();
  277. this.indexFlag = true; // 标志已经到达主页了
  278. }
  279. },
  280. topic: function(topic_id) {
  281. if (g_user && g_user.id != undefined) {
  282. this.appView.showMessage(topic_id);
  283. //this.userView.show(g_user.username);
  284. this.loginView.hide();
  285. this.indexFlag = true; // 标志已经到达主页了
  286. }
  287. },
  288. });
  289. var appRouter = new AppRouter();
  290. //var g_user=new User;
  291. //Backbone.history.start();
  292. //appRouter.navigate('index', {trigger: true});
  293. var g_user = new User;
  294. g_user.fetch({
  295. success: function(model, resp, options){
  296. g_user = resp;
  297. Backbone.history.start({pustState: true});
  298. //g_user={"id":1,"username":"ff"};
  299. if(g_user === null || g_user.id === undefined) {
  300. // 跳转到登录页面
  301. appRouter.navigate('login', {trigger: true});
  302. } else if (appRouter.indexFlag == false){
  303. // 跳转到首页
  304. appRouter.navigate('index', {trigger: true});
  305. }
  306. },
  307. error: function(model, resp, options) {
  308. alert(resp.responseText);
  309. }
  310. }); // 获取当前用户
  311. /*
  312. var Product = Backbone.Model.extend({
  313. urlRoot:"/product",
  314. defaults:function(){
  315. return {
  316. title:"",
  317. price:-1,
  318. discountPrice:-1,
  319. description:"",
  320. imgPath:""
  321. };
  322. }
  323. });
  324. var ProductList = Backbone.Collection.extend({
  325. url:"/products/",
  326. model:Product,
  327. //comparator: 'price'
  328. });
  329. //var products = new ProductList;
  330. var ProductView = Backbone.View.extend({
  331. //tagName:"li",
  332. template: _.template($("#tpl_product").html()),
  333. initialize: function(){
  334. //this.listenTo(this.model, 'change', this.render);
  335. //this.listenTo(this.model, 'destroy', this.remove);
  336. //this.render();
  337. },
  338. render:function(){
  339. this.$el.html(this.template(this.model.toJSON()));
  340. //this.$el.toggleClass("done",this.model.get("done"));
  341. //this.input=this.$(".edit");
  342. return this;
  343. },
  344. events:{
  345. "click .u-product":"onClickProduct",
  346. },
  347. onClickProduct:function(){
  348. //this.model.toggle();
  349. alert(this.model.get("title")+" clicked");
  350. appView.page="detail";
  351. }
  352. });
  353. var AppView = Backbone.View.extend({
  354. el:$("#mymall"),
  355. //page:"list",
  356. //statusTemplate:_.template($("#tpl_status").html()),
  357. initialize:function(){
  358. this.page="list";
  359. this.listenTo(products, 'add', this.addOne);
  360. //this.listenTo(this.page,'all',this.changePage);
  361. this.bind("change:page",function(){
  362. var name= this.get("page");
  363. alert("name变成了:"+name);
  364. });
  365. products.fetch();
  366. //this.render();
  367. },
  368. render:function(){
  369. alert("r");
  370. products.each(function(product){
  371. var view = new ProductView({model: product});
  372. var _html=view.render().el;
  373. this.$(".m-productList").append(view.render().el);
  374. });
  375. },
  376. events:{
  377. "keypress #new_todo": "createOnEnter",
  378. },
  379. createOnEnter:function(e){
  380. //alert(1);
  381. },
  382. addOne:function(product){
  383. var view = new ProductView({model: product});
  384. //var _html=view.render().$el;
  385. this.$(".m-productList").append(view.render().$el.html());
  386. },
  387. changePage:function(page){
  388. alert(page);
  389. }
  390. });
  391. */
  392. })(jQuery);