PageRenderTime 69ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/city_aware/templates/backbone_ex.html

https://github.com/hack4reno2011/Rock-Star-Scientists
HTML | 253 lines | 234 code | 19 blank | 0 comment | 0 complexity | 048f20cdf560798d1ff02b2121d16334 MD5 | raw file
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title></title>
  7. <meta name="viewport" content="width=device-width,initial-scale=1">
  8. <link rel="stylesheet" href="/static/css/style.css">
  9. <script src="/static/js/jquery.js"></script>
  10. <script src="/static/js/underscore.js"></script>
  11. <script src="/static/js/backbone.js"></script>
  12. <style type="text/css">
  13. .editHolder {
  14. width:500px;
  15. }
  16. .label {
  17. width:500px;
  18. clear:both;
  19. }
  20. .options {
  21. float:right;
  22. }
  23. </style>
  24. <script>
  25. var itemTemp = '<span style="color:black;"><%= name %> <%= id %></span><span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>'
  26. var itemTemp2 = '<div class="label"><%= name %> <%= id %><div class="options"><button class="delete">x</button></div>'
  27. var noIdItem = '<div class="label"><%= longform %>(<%= latitude %>,<%= longitude %>)<div class="options"><button class="delete">x</button></div></div>'
  28. var editTemp = '<div class="editHolder"><input class="labelInput" value="<%= longform %>"></input><div class="options"><button class="delete">x</button></div></div>'
  29. //var data = [{'name': "USA"}, {'name': "UK"}, {'name': "France"}];
  30. var data = []
  31. $(function() {
  32. var Item = Backbone.Model.extend({
  33. defaults: {'longform': "Unknown"},
  34. urlRoot: '/api/rawaddress/',
  35. //url: function() {
  36. // console.log("calling url");
  37. // var base = '/api/testdata/';
  38. // if (this.isNew()) {
  39. // return base;
  40. // } else {
  41. // return base + this.id + '/'; //don't forget the slash!
  42. // }
  43. //},
  44. //parse: function(resp, xhr) {
  45. // console.log("parse:", resp, xhr);
  46. //}
  47. });
  48. var List = Backbone.Collection.extend({
  49. model: Item,
  50. url: '/api/rawaddress/',
  51. parse: function(data) {
  52. console.log("PARSING!");
  53. console.log(data);
  54. return data.objects;
  55. },
  56. comparator: function(country) {
  57. return -country.get('id');
  58. }
  59. });
  60. var ItemView = Backbone.View.extend({
  61. tagName: 'li',
  62. className: 'green',
  63. events: {
  64. 'click button.delete': 'remove',
  65. 'dblclick div.label': "editLabel",
  66. },
  67. initialize: function() {
  68. _.bindAll(this, 'render', 'unrender', 'swap', 'remove', 'editLabel', 'saveLabel');
  69. this.model.bind('change', this.render);
  70. this.model.bind('remove', this.unrender);
  71. },
  72. render: function() {
  73. $(this.el).html(_.template(noIdItem, this.model.toJSON()));
  74. return this;
  75. },
  76. editLabel: function() {
  77. console.log("editing label!");
  78. //change the template to editing mode
  79. $(this.el).html(_.template(editTemp, this.model.toJSON()))
  80. $('input.labelInput', this.el).change(this.saveLabel);
  81. return this;
  82. },
  83. saveLabel: function() {
  84. console.log("SAVING LABEL!");
  85. //TODO confirm new text, delete if empty
  86. var newText = $('input.labelInput', this.el).val();
  87. console.log("CHANGED TEXT:", newText);
  88. this.model.set({'longform': newText});
  89. this.model.save();
  90. },
  91. unrender: function() {
  92. $(this.el).remove();
  93. },
  94. swap: function() {
  95. this.model.set({'longform': this.model.get('cid'), 'cid': this.model.get('longform')});
  96. },
  97. remove: function() {
  98. //this.model.destroy();
  99. console.log("preparing to destroy:", this.model);
  100. this.model.destroy({error: function(model, response) {
  101. console.log("DELETE error:", response);
  102. },
  103. success: function(model, response) {
  104. //apparently, reports success on 301 ?!?!
  105. console.log("DELETE success:", model, response);
  106. }
  107. });
  108. }
  109. });
  110. var iList = (new List()).add(data);
  111. var AppView = Backbone.View.extend({
  112. el: $('body'),
  113. events: {
  114. 'click button#refresh': "refreshList",
  115. 'click button#new': "newItem",
  116. 'click button#save': "saveList",
  117. 'click button#sortByName': "sortByName",
  118. 'click button#sortById': "sortById",
  119. },
  120. initialize: function() {
  121. _.bindAll(this, 'render', 'addItem', 'appendItem', 'saveList', 'sortByName', 'renderList', 'sortById', 'newItem', 'refreshList');
  122. this.collection = iList.bind('add', this.appendItem);
  123. this.counter = 0;
  124. this.sortOrder = -1;
  125. this.render();
  126. this.collection = iList.bind('reset', this.renderList);
  127. this.collection.fetch({data: {latitude__lt: 39.52, latitude__gt: 39.50}}); //fires 'reset'
  128. //this.collection.fetch({add: true}); //otherwise list will 'reset'
  129. //this.collection.fetch({add: true, data: {offset: 50}}); //otherwise list will 'reset'
  130. //does collection sort upon 'reset'?
  131. //this.collection.sort(); //should fire 'reset'
  132. },
  133. render: function() {
  134. $(this.el).append("<button id='refresh'>Refresh</button>").append("<button id='sortByName'>Sort by Name</button>").append("<button id='sortById'>Sort by ID</button>").append("<input type='text'></input>").append("<button id='new'>New Item</button>").append("<ul></ul>");
  135. this.renderList();
  136. },
  137. renderList: function() {
  138. $('ul', this.el).empty();
  139. console.log("appending", this.collection.models.length,
  140. "default objects");
  141. //_ each?
  142. for (var i = 0; i < this.collection.models.length; i++) {
  143. this.appendItem(this.collection.models[i]);
  144. }
  145. },
  146. addItem: function() {
  147. console.log("CREATING ITEM!");
  148. //this.counter++
  149. this.collection.add(new Item({'longform': "new item"}));
  150. },
  151. appendItem: function(item) {
  152. //console.log("APPENDING ITEM:", item);
  153. var itemView = new ItemView({
  154. model: item
  155. });
  156. $('ul', this.el).append(itemView.render().el);
  157. },
  158. saveList: function() {
  159. console.log("ATTEMPTING TO SAVE!"); //necessary?
  160. },
  161. sortByName: function() {
  162. this.sortOrder = -this.sortOrder;
  163. this.collection.comparator = buildNameComparator(this.sortOrder);
  164. console.log("SORT?", this.sortOrder);
  165. this.collection.sort();
  166. },
  167. sortById: function() {
  168. this.sortOrder = -this.sortOrder;
  169. this.collection.comparator = buildIdComparator(this.sortOrder);
  170. this.collection.sort();
  171. },
  172. newItem: function() {
  173. console.log("NEW ITEM!");
  174. var newText = $('input', this.el).val();
  175. if (newText) {
  176. //TODO not empty?
  177. //console.log("NEW TEXT:", newText);
  178. var randItem = new Item({'longform': newText});
  179. randItem.save({}, {success: buildSuccessReponse(this.collection)});
  180. var newText = $('input', this.el).val("");
  181. }
  182. //randItem.save(randItem);
  183. //randItem.save({}, {success: buildSuccessReponse(this.collection)});
  184. //randItem.save({}, {error: function(model, response) {
  185. // console.log("CREATE ERROR:", model, response);
  186. // },
  187. // success: function(model, response) {
  188. // //apparently, reports success on 301 ?!?!
  189. // console.log("CREATE SUCCESS:", model, response);
  190. // }
  191. //});
  192. //this.appendItem(randItem);
  193. //this.renderList();
  194. },
  195. refreshList: function() {
  196. console.log("refresh collection");
  197. this.collection.fetch(); //fires 'reset'
  198. }
  199. });
  200. function buildIdComparator(sortOrder) {
  201. return function(country) {
  202. return sortOrder * country.get('id');
  203. }
  204. }
  205. function buildNameComparator(sortOrder) {
  206. return function(Model) {
  207. var str = Model.get("longform");
  208. str = str.toLowerCase();
  209. str = str.split("");
  210. str = _.map(str, function(letter) {
  211. return String.fromCharCode(sortOrder * (letter.charCodeAt(0)));
  212. });
  213. return str;
  214. }
  215. }
  216. function buildSuccessReponse(collection) {
  217. return function(model, response) {
  218. console.log("POST success", model, response);
  219. console.log(model.parse(response));
  220. collection.add(model);
  221. collection.sort();
  222. }
  223. }
  224. var app = new AppView();
  225. });
  226. </script>
  227. </head>
  228. <body>
  229. <div id="container">
  230. <div id="main">
  231. </div>
  232. </div>
  233. </body>
  234. </html>