file-upload.js (2761B)
1 ( function ( $, wp, rwmb ) { 2 'use strict'; 3 4 var views = rwmb.views = rwmb.views || {}, 5 MediaField = views.MediaField, 6 FileUploadField, UploadButton; 7 8 FileUploadField = views.FileUploadField = MediaField.extend( { 9 createAddButton: function () { 10 this.addButton = new UploadButton( {controller: this.controller} ); 11 } 12 } ); 13 14 UploadButton = views.UploadButton = Backbone.View.extend( { 15 className: 'rwmb-upload-area', 16 tagName: 'div', 17 template: wp.template( 'rwmb-upload-area' ), 18 render: function () { 19 this.$el.html( this.template( {} ) ); 20 return this; 21 }, 22 23 initialize: function ( options ) { 24 this.controller = options.controller; 25 this.el.id = _.uniqueId( 'rwmb-upload-area-' ); 26 this.render(); 27 28 // Auto hide if you reach the max number of media 29 this.listenTo( this.controller, 'change:full', function () { 30 this.$el.toggle( ! this.controller.get( 'full' ) ); 31 } ); 32 }, 33 34 // Initializes plupload using code from wp.Uploader (wp-includes/js/plupload/wp-plupload.js) 35 initUploader: function () { 36 var self = this, 37 extensions = this.getExtensions().join( ',' ), 38 maxFileSize = this.controller.get( 'maxFileSize' ), 39 options = { 40 container: this.el, 41 dropzone: this.el, 42 browser: this.$( '.rwmb-browse-button' ), 43 params: { 44 post_id : $( '#post_ID' ).val() 45 }, 46 added: function( attachment ) { 47 self.controller.get( 'items' ).add( [attachment] ); 48 } 49 }; 50 51 // Initialize the plupload instance. 52 this.uploader = new wp.Uploader( options ); 53 54 var filters = this.uploader.uploader.getOption( 'filters' ); 55 if ( maxFileSize ) { 56 filters.max_file_size = maxFileSize; 57 } 58 if ( extensions ) { 59 filters.mime_types = [{title: i18nRwmbMedia.select, extensions: extensions}]; 60 } 61 this.uploader.uploader.setOption( 'filters', filters ); 62 }, 63 64 getExtensions: function () { 65 var mimeTypes = this.controller.get( 'mimeType' ).split( ',' ), 66 exts = []; 67 68 _.each( mimeTypes, function ( current, index ) { 69 if ( i18nRwmbMedia.extensions[current] ) { 70 exts = exts.concat( i18nRwmbMedia.extensions[current] ); 71 } 72 } ); 73 return exts; 74 } 75 } ); 76 77 function initFileUpload() { 78 var $this = $( this ), 79 view = $this.data( 'view' ); 80 81 if ( view ) { 82 return; 83 } 84 85 view = new FileUploadField( { input: this } ); 86 87 $this.siblings( '.rwmb-media-view' ).remove(); 88 $this.after( view.el ); 89 90 // Init uploader after view is inserted to make wp.Uploader works. 91 view.addButton.initUploader(); 92 93 $this.data( 'view', view ); 94 } 95 96 function init( e ) { 97 $( e.target ).find( '.rwmb-file_upload' ).each( initFileUpload ); 98 } 99 100 rwmb.$document 101 .on( 'mb_ready', init ) 102 .on( 'clone', '.rwmb-file_upload', initFileUpload ) 103 } )( jQuery, wp, rwmb );