Skip to content

Instantly share code, notes, and snippets.

@benzkji
Last active August 29, 2015 14:06
Show Gist options
  • Save benzkji/2cbcdad4a347ec16865a to your computer and use it in GitHub Desktop.
Save benzkji/2cbcdad4a347ec16865a to your computer and use it in GitHub Desktop.
backbone model parse and sync customizations, jquy fileupload with backbone forms
// backbone form editor (form field)
Backbone.Form.editors.SingleFileUpload = Backbone.Form.editors.Base.extend ({
//tagName:"input",
_self: false,
uploader: false,
template:false,
template_id: "#singleFileUploadTemplate",
additional_fields: [],
events: {
'change': function() {
// The 'change' event should be triggered whenever something happens
// that affects the result of `this.getValue()`.
this.trigger('change', this);
},
'focus': function() {
// The 'focus' event should be triggered whenever an input within
// this editor becomes the `document.activeElement`.
this.trigger('focus', this);
// This call automatically sets `this.hasFocus` to `true`.
},
'blur': function() {
// The 'blur' event should be triggered whenever an input within
// this editor stops being the `document.activeElement`.
this.trigger('blur', this);
// This call automatically sets `this.hasFocus` to `false`.
},
'click a.single-file-upload_select': 'select_file',
'change .file_include': 'update_included_field_value',
'dummy': function() {}
},
initialize: function(options) {
// Call parent constructor
//_self = this;
Backbone.Form.editors.Base.prototype.initialize.call(this, options);
if (_.has(options.schema, 'template_id')) {
this.template_id = options.schema.template_id;
}
// Custom setup code.
//if (this.schema.customParam) this.doSomething();
},
select_file: function(e) {
e.preventDefault();
this.$el.find('.single-file-upload-hidden').trigger('click');
},
update_included_field_value: function(e) {
this.value[$(e.target).attr('name')] = $(e.target).val();
},
render: function() {
if (!this.template) {
this.template = Handlebars.compile($(this.template_id).html());
}
var context = {
value: this.value,
id: this.id,
key: this.key,
};
if (this.value && 'path' in this.value) {
var version = _.has(this.schema, 'version') ? this.schema.version : "extra" ;
context['src'] = window.base_s3_url + this.value['path'] + version + "." + this.value.pictureFormat + "?" + Math.random();
} else {
this.value = {};
}
this.setValue(this.value);
this.renderTemplate(context);
var _self = this;
$(this.el).fileupload({
paramName: 'file',
dropZone: this.$el.find('.dropZone'),
formData: [],
url: window.cooala_ws_url + "/webadmin/uploadfile",
add: function(e, data) {
_self.$el.find('.single-file-upload-file_dropper_text').hide(0);
_self.$el.find('.single-file-upload-file_percent').show(0);
data.submit();
},
fail: function(e, data) {
_self.$el.find('.single-file-upload-file_dropper_text').show(0);
_self.$el.find('.single-file-upload-file_percent').hide(0);
alert('Upload failed - your file is either too heavy ( > 5mb ) or in a awkward format.');
},
done: function(e, data) {
// ui
_self.$el.find('.single-file-upload-file_dropper_text').show(0);
_self.$el.find('.single-file-upload-file_percent').hide(0);
//_self.$el.find('.single-file-upload-preview_image').html('<b>Ready:</b> ' + data.files[0].name + '<br><br>');
var version = _self.schema.version ? _self.schema.version.toUpperCase() : "EXTRA";
var src = window.cooala_ws_url + "/webadmin/preview/" + data.result.id + "?size=" + version +"&type=" + _self.schema.pictureType;
_self.$el.find('.single-file-upload-preview_image').html('<img src="' + src + '"><br><br>');
// data
_self.value['id'] = data.result.id;
_self.value['isNew'] = "true";
if (_self.schema.pictureType) {
_self.value['pictureType'] = _self.schema.pictureType;
}
_self.setValue(_self.value);
},
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
_self.$el.find('.single-file-upload-file_percent span').html(progress + "%");
}
});
return this;
},
getValue: function() {
//return this.$el.val();
return this.value;
},
setValue: function(value) {
//this.$el.val(value);
this.value = value;
},
focus: function() {
if (this.hasFocus) return;
// This method call should result in an input within this edior
// becoming the `document.activeElement`.
// This, in turn, should result in this editor's `focus` event
// being triggered, setting `this.hasFocus` to `true`.
// See above for more detail.
this.$el.focus();
},
blur: function() {
if (!this.hasFocus) return;
this.$el.blur();
}
});
<!-- singleFileUpload backbone form editor. -->
<script class="template" id="singleFileUploadTemplate" type="template/handlebars">
<div class="single-file-upload-preview_image">{{#if src}}<img src="{{src}}"><br><br>{{else}} {{/if}}</div>
<div class="single-file-upload-upload_section">
<div id="single-file-upload-file_dropper_{{id}}" class="dropZone single-file-upload-file_dropper">
<span class="single-file-upload-file_dropper_text">drag new image here</span>
<span class="single-file-upload-file_percent">
<img src="{% endverbatim %}{{STATIC_URL}}{% verbatim %}cooaladmin/images/loader.gif">
&nbsp;&nbsp;<span></span>
</span>
</div>
<p>or <a id="single-file-upload_select_{{id}}" class="single-file-upload_select" href="#">select one</a> (max. 5mb)<br>(best: .svg, .png / if not: .jpg, .gif, .tif)</p></div>
<div style="clear:both;"></div>
<input id="id_file_{{key}}" type="file" value="" name="{{key}}" class="single-file-upload-hidden">
</script>
// MyModel.js
{
parse: function(response) {
if (response && _.has(response, 'myPictureReferences')){
var refs = response['myPictureReferences'];
response['image'] = {};
_.each(refs, function(item) {
if (item['pictureType'] == 'RIGHT_TEASER') {
response['rightImage'] = item;
}
if (item['pictureType'] == 'LEFT_TEASER') {
response['leftImage'] = item;
}
if (item['pictureType'] == 'TEASER') {
response['image'] = item;
}
});
}
return response;
},
sync: function(method, model, options) {
if (method == 'read' || method == "delete") {
return Backbone.sync(method, model, options);
}
var data = model.toJSON();
// more customizing, for example add images...etc.
return util_save_update_ajax(this, method, data, options);
}
}
// utils.js
function util_save_update_ajax(model, method, data, options) {
var ajax_options = _.extend({
type: 'put',
url: model.urlRoot,
data: JSON.stringify(data),
dataType: 'json'
},
options
);
if (method=='update') {
data['id'] = model.get('id');
ajax_options.data = JSON.stringify(data);
return $.ajax(ajax_options);
}
if (method=='create') {
ajax_options = _.extend(ajax_options, {'type': 'post'});
return $.ajax(ajax_options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment