js/src/fields/controls/gallery/GalleryController.js
/**
* Main Field Controller
*/
//KB.Gallery.Controller
var Logger = require('common/Logger');
var ImageView = require('./ImageView');
module.exports = Backbone.View.extend({
initialize: function (params) {
this._frame = null; // media modal instance
this.subviews = []; // image items
this.listenTo(KB.Events, 'modal.saved', this.frontendSave);
this.setupElements();
this.initialSetup();
Logger.Debug.log('Fields: Gallery instance created and initialized');
},
events: {
'click .kb-gallery--js-add-images': 'addImages'
},
setupElements: function () {
// Add list element dynamically
this.$list = jQuery('<div class="kb-gallery--item-list"></div>').appendTo(this.$el);
this.$list.sortable({revert: true, delay: 300});
// add button dynamically
this.$addButton = jQuery('<a class="button button-primary kb-gallery--js-add-images">' + KB.i18n.Refields.image.addButton + '</a>').appendTo(this.$el);
},
addImages: function () {
this.openModal();
},
frame: function () {
if (this._frame) {
return this._frame;
}
},
openModal: function () {
var that = this;
// opens dialog if not already declared
if (this._frame) {
this._frame.open();
return;
}
this._frame = wp.media({
// Custom attributes
title: KB.i18n.Refields.image.modalHelpTitle,
button: {
text: KB.i18n.Refields.common.select
},
multiple: true,
library: {
type: 'image'
}
});
this._frame.state('library').on('select', function () {
that.select(this);
});
this._frame.open();
return this._frame;
},
select: function (modal) {
var selection = modal.get('selection');
if (selection.length > 0) {
this.handleModalSelection(selection.models);
}
},
handleModalSelection: function (selection) {
var that = this;
_.each(selection, function (image) {
var attr = {
file: image.toJSON(),
details: {
'title': '',
'alt': '',
'description': ''
},
id: image.get('id')
};
var model = new Backbone.Model(attr);
var imageView = new ImageView({model: model, Controller: that});
that.subviews.push(imageView);
that.$list.append(imageView.render());
setTimeout(function () {
KB.Events.trigger('modal.recalibrate');
}, 250);
})
},
initialSetup: function () {
var that = this;
var data = this.model.get('value').images || {};
if (_.toArray(data).length > 0) {
_.each(data, function (image) {
var model = new Backbone.Model(image);
var imageView = new ImageView({model: model, Controller: that});
that.subviews.push(imageView);
that.$list.append(imageView.render());
})
}
},
frontendSave: function () {
var that = this;
if (this.subviews.length > 0) {
_.each(this.subviews, function (m, i) {
if (m._remove) {
delete that.subviews[i];
m.remove();
}
});
}
}
});