Permalink
Browse files

Use utils and models from Shareabouts.js

  • Loading branch information...
1 parent 3aa5508 commit c00f83a48af8e1f3196ca606603a01d86cf0913e @atogle atogle committed Mar 21, 2013
View
45 src/sa_web/static/js/models.js
@@ -1,12 +1,16 @@
+/*global _ Backbone jQuery */
+
var Shareabouts = Shareabouts || {};
-(function(S, $, console, loadImage) {
+(function(S, $) {
+ 'use strict';
+
var normalizeModelArguments = function(key, val, options) {
var attrs;
- if (key == null || _.isObject(key)) {
+ if (key === null || _.isObject(key)) {
attrs = key;
options = val;
- } else if (key != null) {
+ } else if (key !== null) {
(attrs = {})[key] = val;
}
options = options ? _.clone(options) : {};
@@ -17,7 +21,24 @@ var Shareabouts = Shareabouts || {};
};
};
- S.SubmissionModel = Backbone.Model.extend({
+ S.ShareaboutsApiModel = Backbone.Model.extend({
+ sync: function(method, model, options) {
+ var data = model.toJSON();
+
+ delete data.created_datetime;
+ delete data.dataset;
+ delete data.id;
+ delete data.updated_datetime;
+
+ options = options || {};
+ options.contentType = 'application/json';
+ options.data = JSON.stringify(data);
+
+ Backbone.sync(method, model, options);
+ }
+ });
+
+ S.SubmissionModel = S.ShareaboutsApiModel.extend({
url: function() {
// This is to make Django happy. I'm sad to have to add it.
var url = S.SubmissionModel.__super__.url.call(this);
@@ -46,7 +67,7 @@ var Shareabouts = Shareabouts || {};
}
});
- S.PlaceModel = Backbone.Model.extend({
+ S.PlaceModel = S.ShareaboutsApiModel.extend({
initialize: function(attributes, options) {
this.responseCollection = new S.SubmissionCollection([], {
placeModel: this,
@@ -122,12 +143,14 @@ var Shareabouts = Shareabouts || {};
// Pass the submissionType into each PlaceModel so that it makes its way
// to the SubmissionCollections
options = options || {};
- options.responseType = this.options.responseType;
- options.supportType = this.options.supportType;
+ options.responseType = this.options && this.options.responseType;
+ options.supportType = this.options && this.options.supportType;
return S.PlaceCollection.__super__.add.call(this, models, options);
}
});
+ // This does not support editing at this time, which is why it is not a
+ // ShareaboutsModel
S.AttachmentModel = Backbone.Model.extend({
idAttr: 'name',
@@ -196,9 +219,9 @@ var Shareabouts = Shareabouts || {};
url: '/api/activity/'
});
-})(Shareabouts, jQuery, Shareabouts.Util.console, window.loadImage);
-// NOTE: loadImage comes from the Load Image plugin in load-image.js
+}(Shareabouts, jQuery, Shareabouts.Util.console));
+/*global jQuery */
/*****************************************************************************
@@ -222,12 +245,12 @@ https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/
jQuery(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
- if (document.cookie && document.cookie != '') {
+ if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
- if (cookie.substring(0, name.length + 1) == (name + '=')) {
+ if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
View
1 src/sa_web/static/js/models.min.js
@@ -0,0 +1 @@
+var Shareabouts=Shareabouts||{};(function(t,e){"use strict";var n=function(t,e,n){var o;return null===t||_.isObject(t)?(o=t,n=e):null!==t&&((o={})[t]=e),n=n?_.clone(n):{},{options:n,attrs:o}};t.ShareaboutsApiModel=Backbone.Model.extend({sync:function(t,e,n){var o=e.toJSON();delete o.created_datetime,delete o.dataset,delete o.id,delete o.updated_datetime,n=n||{},n.contentType="application/json",n.data=JSON.stringify(o),Backbone.sync(t,e,n)}}),t.SubmissionModel=t.ShareaboutsApiModel.extend({url:function(){var e=t.SubmissionModel.__super__.url.call(this);return e+="/"===e.charAt(e.length-1)?"":"/"}}),t.SubmissionCollection=Backbone.Collection.extend({initialize:function(t,e){this.options=e},model:t.SubmissionModel,url:function(){var t=this.options.submissionType,e=this.options.placeModel.id;if(!e)throw Error("Place model id is not defined. You must save the Place before saving its "+t+".");return"/api/places/"+e+"/"+t+"/"}}),t.PlaceModel=t.ShareaboutsApiModel.extend({initialize:function(e,n){this.responseCollection=new t.SubmissionCollection([],{placeModel:this,submissionType:n.responseType}),this.supportCollection=new t.SubmissionCollection([],{placeModel:this,submissionType:n.supportType});var o=this.get("attachments")||[];this.attachmentCollection=new t.AttachmentCollection(o,{thingModel:this})},set:function(e,o,a){var i=n(e,o,a);return _.isArray(i.attrs.attachments)&&this.attachmentCollection&&!i.options.ignoreAttachnments&&this.attachmentCollection.reset(i.attrs.attachments),t.PlaceModel.__super__.set.call(this,i.attrs,i.options)},save:function(o,a,i){var s,r=this,c=n(o,a,i),l=c.attrs;i=c.options,this.isNew()?(s=i.success||e.noop,i.success=function(){r.saveAttachments(),s.apply(this,arguments)}):r.saveAttachments(),i.ignoreAttachnments=!0,t.PlaceModel.__super__.save.call(this,l,i)},saveAttachments:function(){this.attachmentCollection.each(function(t){t.isNew()&&t.save()})}}),t.PlaceCollection=Backbone.Collection.extend({url:"/api/places/",model:t.PlaceModel,initialize:function(t,e){this.options=e},add:function(e,n){return n=n||{},n.responseType=this.options&&this.options.responseType,n.supportType=this.options&&this.options.supportType,t.PlaceCollection.__super__.add.call(this,e,n)}}),t.AttachmentModel=Backbone.Model.extend({idAttr:"name",initialize:function(t,e){this.options=e},save:function(t,e,o){var a=n(t,e,o),i=_.extend(this.attributes,a.attrs);return this._attachBlob(i.blob,i.name,a.options)},_attachBlob:function(n,o,a){var i=new FormData,s=t.Util.wrapHandler("progress",this,a.progress),r=e.ajaxSettings.xhr();i.append("file",n),i.append("name",o),a=a||{},e.ajax({url:this.collection.url(),type:"POST",xhr:function(){return r.upload&&r.upload.addEventListener("progress",s,!1),r},success:a.success,error:a.error,data:i,cache:!1,contentType:!1,processData:!1})}}),t.AttachmentCollection=Backbone.Collection.extend({model:t.AttachmentModel,initialize:function(t,e){this.options=e},url:function(){var t=this.options.thingModel,e=t.url();return e+"/attachments/"}}),t.ActivityCollection=Backbone.Collection.extend({url:"/api/activity/"})})(Shareabouts,jQuery,Shareabouts.Util.console),jQuery(document).ajaxSend(function(t,e,n){function o(t){var e=null;if(document.cookie&&""!==document.cookie)for(var n=document.cookie.split(";"),o=0;n.length>o;o++){var a=jQuery.trim(n[o]);if(a.substring(0,t.length+1)===t+"="){e=decodeURIComponent(a.substring(t.length+1));break}}return e}function a(t){var e=document.location.host,n=document.location.protocol,o="//"+e,a=n+o;return t==a||t.slice(0,a.length+1)==a+"/"||t==o||t.slice(0,o.length+1)==o+"/"||!/^(\/\/|http:|https:).*/.test(t)}function i(t){return/^(GET|HEAD|OPTIONS|TRACE)$/.test(t)}!i(n.type)&&a(n.url)&&e.setRequestHeader("X-CSRFToken",o("csrftoken")),"DELETE"===n.type&&(e.setRequestHeader("Content-Type","application/json"),n.data="{}")});
View
73 src/sa_web/static/js/utils.js
@@ -1,6 +1,10 @@
+/*global _ moment BinaryFile loadImage EXIF */
+
var Shareabouts = Shareabouts || {};
-(function(S, moment){
+(function(S){
+ 'use strict';
+
S.Util = {
setPrettyDateLang: function(locale) {
moment.lang(locale);
@@ -18,7 +22,7 @@ var Shareabouts = Shareabouts || {};
var attrs = {};
// Get values from the form
- _.each($form.serializeArray(), function(item, i) {
+ _.each($form.serializeArray(), function(item) {
attrs[item.name] = item.value;
});
@@ -60,7 +64,7 @@ var Shareabouts = Shareabouts || {};
},
fixImageOrientation: function(canvas, orientation) {
- var rotated = document.createElement("canvas"),
+ var rotated = document.createElement('canvas'),
ctx = rotated.getContext('2d'),
width = canvas.width,
height = canvas.height;
@@ -154,6 +158,67 @@ var Shareabouts = Shareabouts || {};
}
};
return newHandler;
+ },
+
+ callWithRetries: function(func, retryCount, context) {
+ var args = Array.prototype.slice.call(arguments, 3),
+ options = _.last(args),
+ errorHandler = options.error,
+ retries = 0;
+
+ if (!options) {
+ options = {};
+ args.push(options);
+ }
+
+ options.error = function() {
+ if (retries < retryCount) {
+ retries++;
+ setTimeout(function() {
+ func.apply(context, args);
+ }, retries * 100);
+ } else {
+ if (errorHandler) {
+ errorHandler.apply(context, arguments);
+ }
+ }
+ };
+
+ func.apply(context, args);
+ },
+
+ // Cookies! Om nom nom
+ // Thanks ppk! http://www.quirksmode.org/js/cookies.html
+ cookies: {
+ save: function(name,value,days) {
+ var expires;
+ if (days) {
+ var date = new Date();
+ date.setTime(date.getTime()+(days*24*60*60*1000));
+ expires = '; expires='+date.toGMTString();
+ }
+ else {
+ expires = '';
+ }
+ document.cookie = name+'='+value+expires+'; path=/';
+ },
+ get: function(name) {
+ var nameEQ = name + '=';
+ var ca = document.cookie.split(';');
+ for(var i=0;i < ca.length;i++) {
+ var c = ca[i];
+ while (c.charAt(0) === ' ') {
+ c = c.substring(1,c.length);
+ }
+ if (c.indexOf(nameEQ) === 0) {
+ return c.substring(nameEQ.length,c.length);
+ }
+ }
+ return null;
+ },
+ destroy: function(name) {
+ this.save(name,'',-1);
+ }
}
};
-})(Shareabouts, moment);
+}(Shareabouts));
View
1 src/sa_web/static/js/utils.min.js
@@ -0,0 +1 @@
+var Shareabouts=Shareabouts||{};(function(e){"use strict";e.Util={setPrettyDateLang:function(e){moment.lang(e)},getPrettyDateTime:function(e,t){return t?moment(e).format(t):moment(e).fromNow()},getAttrs:function(e){var t={};return _.each(e.serializeArray(),function(e){t[e.name]=e.value}),t},isSupported:function(e){switch(e.browser.name){case"Chrome":case"Firefox":case"Safari":return!0;case"Microsoft Internet Explorer":var t=e.browser.version.indexOf("."),r=parseInt(e.browser.version.substr(0,t),10);if(r>7)return!0}return!1},fileInputSupported:function(){var e=document.createElement("input");return e.setAttribute("type","file"),e.disabled===!1},console:window.console||{log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){}},fixImageOrientation:function(e,t){var r=document.createElement("canvas"),a=r.getContext("2d"),n=e.width,i=e.height;switch(t){case 5:case 6:case 7:case 8:r.width=e.height,r.height=e.width;break;default:r.width=e.width,r.height=e.height}switch(t){case 1:break;case 2:a.translate(n,0),a.scale(-1,1);break;case 3:a.translate(n,i),a.rotate(Math.PI);break;case 4:a.translate(0,i),a.scale(1,-1);break;case 5:a.rotate(.5*Math.PI),a.scale(1,-1);break;case 6:a.rotate(.5*Math.PI),a.translate(0,-i);break;case 7:a.rotate(.5*Math.PI),a.translate(n,-i),a.scale(-1,1);break;case 8:a.rotate(-.5*Math.PI),a.translate(-n,0);break;default:}return a.drawImage(e,0,0),r},fileToCanvas:function(t,r,a){var n=new FileReader;n.onloadend=function(){var n=EXIF.readFromBinaryFile(new BinaryFile(this.result)),i=n.Orientation;loadImage(t,function(t){var a=e.Util.fixImageOrientation(t,i);r(a)},a)},n.readAsBinaryString(t)},wrapHandler:function(e,t,r){var a=function(a){t.trigger(e,a),r&&r.apply(this,arguments)};return a},callWithRetries:function(e,t,r){var a=Array.prototype.slice.call(arguments,3),n=_.last(a),i=n.error,o=0;n||(n={},a.push(n)),n.error=function(){t>o?(o++,setTimeout(function(){e.apply(r,a)},100*o)):i&&i.apply(r,arguments)},e.apply(r,a)},cookies:{save:function(e,t,r){var a;if(r){var n=new Date;n.setTime(n.getTime()+1e3*60*60*24*r),a="; expires="+n.toGMTString()}else a="";document.cookie=e+"="+t+a+"; path=/"},get:function(e){for(var t=e+"=",r=document.cookie.split(";"),a=0;r.length>a;a++){for(var n=r[a];" "===n.charAt(0);)n=n.substring(1,n.length);if(0===n.indexOf(t))return n.substring(t.length,n.length)}return null},destroy:function(e){this.save(e,"",-1)}}}})(Shareabouts);

0 comments on commit c00f83a

Please sign in to comment.