PageRenderTime 60ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/netbeans-7.3/web.client.samples/EaselDemo/public_html/rest/RestClient.js

https://gitlab.com/essere.lab.public/qualitas.class-corpus
JavaScript | 378 lines | 285 code | 26 blank | 67 comment | 15 complexity | 0f20f77ee8f16ede8396ff346d3ad338 MD5 | raw file
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. var app = {
  6. // Create this closure to contain the cached modules
  7. module: function() {
  8. // Internal module cache.
  9. var modules = {};
  10. // Create a new module reference scaffold or load an
  11. // existing module.
  12. return function(name) {
  13. // If this module has already been created, return it.
  14. if (modules[name]) {
  15. return modules[name];
  16. }
  17. // Create a module and save it under this name
  18. return modules[name] = {Views: {}};
  19. };
  20. }()
  21. };
  22. (function(models) {
  23. // Model for Manufacturer entity
  24. models.Manufacturer = Backbone.Model.extend({
  25. urlRoot: "rest/resources/manufacturer.json",
  26. idAttribute: 'manufacturerId',
  27. defaults: {
  28. addressline2: "",
  29. zip: "",
  30. phone: "",
  31. fax: "",
  32. addressline1: "",
  33. email: "",
  34. name: "",
  35. state: "",
  36. rep: "",
  37. city: ""
  38. },
  39. toViewJson: function() {
  40. var result = this.toJSON(); // displayName property is used to render item in the list
  41. result.displayName = this.get('name');
  42. return result;
  43. },
  44. isNew: function() {
  45. // default isNew() method imlementation is
  46. // based on the 'id' initialization which
  47. // sometimes is required to be initialized.
  48. // So isNew() is rediefined here
  49. return this.notSynced;
  50. },
  51. sync: function(method, model, options) {
  52. options || (options = {});
  53. var errorHandler = {
  54. error: function(jqXHR, textStatus, errorThrown) {
  55. // TODO: put your error handling code here
  56. // If you use the JS client from the different domain
  57. // (f.e. locally) then Cross-origin resource sharing
  58. // headers has to be set on the REST server side.
  59. // Otherwise the JS client has to be copied into the
  60. // some (f.e. the same) Web project on the same domain
  61. alert('Unable to fulfil the request. This is a sample application without server backend.');
  62. }}
  63. if (method == 'create') {
  64. options.url = 'rest/resources/manufacturer.json';
  65. }
  66. if (method == 'update') {
  67. options.url = 'rest/resources/manufacturer.json';
  68. }
  69. var result = Backbone.sync(method, model, _.extend(options, errorHandler));
  70. return result;
  71. }
  72. });
  73. // Collection class for Manufacturer entities
  74. models.ManufacturerCollection = Backbone.Collection.extend({
  75. model: models.Manufacturer,
  76. url: "rest/resources/manufacturer.json",
  77. sync: function(method, model, options) {
  78. options || (options = {});
  79. var errorHandler = {
  80. error: function(jqXHR, textStatus, errorThrown) {
  81. // TODO: put your error handling code here
  82. // If you use the JS client from the different domain
  83. // (f.e. locally) then Cross-origin resource sharing
  84. // headers has to be set on the REST server side.
  85. // Otherwise the JS client has to be copied into the
  86. // some (f.e. the same) Web project on the same domain
  87. alert('Unable to fulfil the request');
  88. }}
  89. var result = Backbone.sync(method, model, _.extend(options, errorHandler));
  90. return result;
  91. }
  92. });
  93. })(app.module("models"));
  94. (function(views) {
  95. views.ListView = Backbone.View.extend({
  96. tagName: 'tbody',
  97. initialize: function() {
  98. this.model.bind("reset", this.render, this);
  99. var self = this;
  100. this.model.bind("add", function(modelName) {
  101. var row = new views.ListItemView({
  102. model: modelName,
  103. templateName: self.options.templateName
  104. }).render().el;
  105. $(self.el).append($(row));
  106. $(self.el).parent().trigger('addRows', [$(row)]);
  107. });
  108. },
  109. render: function(eventName) {
  110. var self = this;
  111. _.each(this.model.models, function(modelName) {
  112. $(this.el).append(new views.ListItemView({
  113. model: modelName,
  114. templateName: self.options.templateName
  115. }).render().el);
  116. }, this);
  117. return this;
  118. }
  119. });
  120. views.ListItemView = Backbone.View.extend({
  121. tagName: 'tr',
  122. initialize: function() {
  123. this.model.bind("change", this.render, this);
  124. this.model.bind("destroy", this.close, this);
  125. },
  126. template: function(json) {
  127. /*
  128. * templateName is element identifier in HTML
  129. * $(this.options.templateName) is element access to the element
  130. * using jQuery
  131. */
  132. return _.template($(this.options.templateName).html())(json);
  133. },
  134. render: function(eventName) {
  135. $(this.el).html(this.template(this.model.toJSON()));
  136. return this;
  137. },
  138. close: function() {
  139. var table = $(this.el).parent().parent();
  140. table.trigger('disable.pager');
  141. $(this.el).unbind();
  142. $(this.el).remove();
  143. table.trigger('enable.pager');
  144. }
  145. });
  146. views.ModelView = Backbone.View.extend({
  147. initialize: function() {
  148. this.model.bind("change", this.render, this);
  149. },
  150. render: function(eventName) {
  151. $(this.el).html(this.template(this.model.toJSON()));
  152. return this;
  153. },
  154. template: function(json) {
  155. /*
  156. * templateName is element identifier in HTML
  157. * $(this.options.templateName) is element access to the element
  158. * using jQuery
  159. */
  160. return _.template($(this.options.templateName).html())(json);
  161. },
  162. /*
  163. * Classes "save" and "delete" are used on the HTML controls to listen events.
  164. * So it is supposed that HTML has controls with these classes.
  165. */
  166. events: {
  167. "change input": "change",
  168. "click .save": "save",
  169. "click .delete": "drop"
  170. },
  171. change: function(event) {
  172. var target = event.target;
  173. console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value);
  174. },
  175. save: function() {
  176. // TODO : put save code here
  177. var hash = this.options.getHashObject();
  178. this.model.set(hash);
  179. if (this.model.isNew() && this.collection) {
  180. var self = this;
  181. this.collection.create(this.model, {
  182. success: function() {
  183. // see isNew() method implementation in the model
  184. self.model.notSynced = false;
  185. self.options.navigate(self.model.id);
  186. }
  187. });
  188. } else {
  189. this.model.save();
  190. this.model.el.parent().parent().trigger("update");
  191. }
  192. return false;
  193. },
  194. drop: function() {
  195. this.model.destroy({
  196. success: function() {
  197. /*
  198. * TODO : put your code here
  199. * f.e. alert("Model is successfully deleted");
  200. */
  201. window.history.back();
  202. }
  203. });
  204. return false;
  205. },
  206. close: function() {
  207. $(this.el).unbind();
  208. $(this.el).empty();
  209. }
  210. });
  211. // This view is used to create new model element
  212. views.CreateView = Backbone.View.extend({
  213. initialize: function() {
  214. this.render();
  215. },
  216. render: function(eventName) {
  217. $(this.el).html(this.template());
  218. return this;
  219. },
  220. template: function(json) {
  221. /*
  222. * templateName is element identifier in HTML
  223. * $(this.options.templateName) is element access to the element
  224. * using jQuery
  225. */
  226. return _.template($(this.options.templateName).html())(json);
  227. },
  228. /*
  229. * Class "new" is used on the control to listen events.
  230. * So it is supposed that HTML has a control with "new" class.
  231. */
  232. events: {
  233. "click .new": "create"
  234. },
  235. create: function(event) {
  236. this.options.navigate();
  237. return false;
  238. }
  239. });
  240. })(app.module("views"));
  241. $(function() {
  242. var models = app.module("models");
  243. var views = app.module("views");
  244. var AppRouter = Backbone.Router.extend({
  245. routes: {
  246. '': 'list',
  247. 'new': 'create'
  248. ,
  249. ':id': 'details'
  250. },
  251. initialize: function() {
  252. var self = this;
  253. $('#create').html(new views.CreateView({
  254. // tpl-create is template identifier for 'create' block
  255. templateName: '#tpl-create',
  256. navigate: function() {
  257. self.navigate('new', true);
  258. }
  259. }).render().el);
  260. },
  261. list: function() {
  262. this.collection = new models.ManufacturerCollection();
  263. var self = this;
  264. this.collection.fetch({
  265. success: function() {
  266. self.listView = new views.ListView({
  267. model: self.collection,
  268. // tpl-manufacturer-list-itemis template identifier for item
  269. templateName: '#tpl-manufacturer-list-item'
  270. });
  271. $('#datatable').html(self.listView.render().el).append(_.template($('#thead').html())());
  272. if (self.requestedId) {
  273. self.details(self.requestedId);
  274. }
  275. var pagerOptions = {
  276. // target the pager markup
  277. container: $('.pager'),
  278. // output string - default is '{page}/{totalPages}'; possiblevariables: {page}, {totalPages},{startRow}, {endRow} and {totalRows}
  279. output: '{startRow} to {endRow} ({totalRows})',
  280. // starting page of the pager (zero based index)
  281. page: 0,
  282. // Number of visible rows - default is 10
  283. size: 10
  284. };
  285. $('#datatable').tablesorter({widthFixed: true,
  286. widgets: ['zebra']}).
  287. tablesorterPager(pagerOptions);
  288. }
  289. });
  290. },
  291. details: function(id) {
  292. if (this.collection) {
  293. this.manufacturer = this.collection.get(id);
  294. if (this.view) {
  295. this.view.close();
  296. }
  297. var self = this;
  298. this.view = new views.ModelView({
  299. model: this.manufacturer,
  300. // tpl-manufacturer-details is template identifier for chosen model element
  301. templateName: '#tpl-manufacturer-details',
  302. getHashObject: function() {
  303. return self.getData();
  304. }
  305. });
  306. $('#details').html(this.view.render().el);
  307. } else {
  308. this.requestedId = id;
  309. this.list();
  310. }
  311. },
  312. create: function() {
  313. if (this.view) {
  314. this.view.close();
  315. }
  316. var self = this;
  317. var dataModel = new models.Manufacturer();
  318. // see isNew() method implementation in the model
  319. dataModel.notSynced = true;
  320. this.view = new views.ModelView({
  321. model: dataModel,
  322. collection: this.collection,
  323. // tpl-manufacturer-details is a template identifier for chosen model element
  324. templateName: '#tpl-manufacturer-details',
  325. navigate: function(id) {
  326. self.navigate(id, false);
  327. },
  328. getHashObject: function() {
  329. return self.getData();
  330. }
  331. });
  332. $('#details').html(this.view.render().el);
  333. },
  334. getData: function() {
  335. return {
  336. manufacturerId: $('#manufacturerId').val(),
  337. addressline2: $('#addressline2').val(),
  338. zip: $('#zip').val(),
  339. phone: $('#phone').val(),
  340. addressline1: $('#addressline1').val(),
  341. fax: $('#fax').val(),
  342. email: $('#email').val(),
  343. name: $('#name').val(),
  344. state: $('#state').val(),
  345. city: $('#city').val(),
  346. rep: $('#rep').val()
  347. };
  348. }
  349. });
  350. new AppRouter();
  351. Backbone.history.start();
  352. });