PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/public/app/image_saver.js

https://bitbucket.org/tweetegy/save_multiple_images_using_backbone
JavaScript | 116 lines | 92 code | 24 blank | 0 comment | 1 complexity | f8a45cb4ca8fd8a4b869edec1fff76e8 MD5 | raw file
  1. $(document).ready(function() {
  2. window.Image = Backbone.Model.extend({
  3. defaults: {
  4. "filename": "preview.png",
  5. "data": "img/preview.png"
  6. }
  7. });
  8. window.Gallery = Backbone.Collection.extend({
  9. model: Image,
  10. url: "/images",
  11. setFromFiles: function(files) {
  12. this.reset();
  13. self = this;
  14. console.log(self);
  15. for (var i = 0, f; f = files[i]; i++) {
  16. var reader = new FileReader();
  17. reader.onload = (function(theFile, theId) {
  18. return function(e) {
  19. image = new window.Image();
  20. image.set({id: theId})
  21. image.set({filename: theFile.name});
  22. image.set({data: e.target.result});
  23. self.add(image);
  24. };
  25. })(f);
  26. reader.readAsDataURL(f,i);
  27. }
  28. }
  29. });
  30. window.ImageView = Backbone.View.extend({
  31. tagName: 'span',
  32. template: _.template($("#image-template").html()),
  33. initialize: function() {
  34. _.bindAll(this, 'render');
  35. },
  36. render: function() {
  37. $(this.el).html(this.template(this.model.toJSON()));
  38. return this;
  39. }
  40. });
  41. window.ImageSelectionView = Backbone.View.extend({
  42. events: {
  43. 'change #myGallery': 'dispatchUpdateGalleryPreview',
  44. 'click #saveGallery': 'dispatchSaveGallery'
  45. },
  46. template: _.template($("#gallery-selection-template").html()),
  47. initialize: function() {
  48. _.bindAll(this, 'render');
  49. },
  50. render: function() {
  51. $(this.el).html(this.template({}));
  52. return this;
  53. },
  54. dispatchSaveGallery: function() {
  55. Backbone.sync("create", this.collection);
  56. },
  57. dispatchUpdateGalleryPreview: function(e) {
  58. this.collection.setFromFiles(e.target.files);
  59. }
  60. });
  61. window.GalleryView = Backbone.View.extend({
  62. template: _.template($("#gallery-template").html()),
  63. initialize: function() {
  64. _.bindAll(this, 'render');
  65. this.collection.bind('add', this.render);
  66. },
  67. render: function(){
  68. var $images,
  69. collection = this.collection;
  70. $(this.el).html(this.template({}));
  71. $images = this.$("#thumbnails");
  72. this.collection.each(function(image) {
  73. var view = new ImageView({
  74. model: image,
  75. collection: collection
  76. });
  77. $images.append(view.render().el);
  78. });
  79. return this;
  80. }
  81. });
  82. window.ImageGalleryRouter = Backbone.Router.extend({
  83. routes: {
  84. '': 'home'
  85. },
  86. home: function(){
  87. $('#container').empty();
  88. $('#container').append(window.galleryView.render().el);
  89. $('#container').append(window.imageSelectionView.render().el);
  90. }
  91. });
  92. });