Input: Reads registered data attributes of a given element from the DOM and updates an existing jQuery data cache with these values . [CODESPLIT] function _updateJQueryDataCache ( $elem ) { var add = { } , remove = [ ] ; if ( $ . hasData ( $elem [ 0 ] ) ) { // A jQuery data cache exists. Update it for the el properties (and attribute names registered by a plugin). // Primitive data types. Normally, this will read the "data-tag-name", "data-class-name" and "data-id" // attributes. _ . each ( registeredDataAttributes . primitives , function ( attributeName ) { var attributeValue = $elem . attr ( "data-" + attributeName ) ; if ( attributeValue === undefined ) { remove . push ( attributeName ) ; } else { add [ toCamelCase ( attributeName ) ] = attributeValue ; } } ) ; // Stringified JSON data. Normally, this just deals with "data-attributes". _ . each ( registeredDataAttributes . json , function ( attributeName ) { var attributeValue = $elem . attr ( "data-" + attributeName ) ; if ( attributeValue === undefined ) { remove . push ( attributeName ) ; } else { try { add [ toCamelCase ( attributeName ) ] = $ . parseJSON ( attributeValue ) ; } catch ( err ) { remove . push ( attributeName ) ; } } } ) ; if ( remove . length ) $elem . removeData ( remove ) ; if ( _ . size ( add ) ) $elem . data ( add ) ; } }


Input: Registers an alternative way to access the cache and set up a custom compiler and loader . Intended for use by plugins . [CODESPLIT] function _registerCacheAlias ( namespaceObject , instanceCachePropertyName ) { namespaceObject . getCachedTemplate = Backbone . DeclarativeViews . getCachedTemplate ; namespaceObject . clearCachedTemplate = Backbone . DeclarativeViews . clearCachedTemplate ; namespaceObject . clearCache = Backbone . DeclarativeViews . clearCache ; namespaceObject . custom = Backbone . DeclarativeViews . custom ; if ( instanceCachePropertyName ) { instanceCacheAliases . push ( instanceCachePropertyName ) ; instanceCacheAliases = _ . unique ( instanceCacheAliases ) ; } }


Input: Checks if an error belongs to the error types of Backbone . DeclarativeViews . [CODESPLIT] function _isDeclarativeViewsErrorType ( error ) { return error instanceof GenericError || error instanceof TemplateError || error instanceof CompilerError || error instanceof CustomizationError || error instanceof ConfigurationError ; }


Input: Marionette integration ---------------------- [CODESPLIT] function joinMarionette ( ) { if ( Backbone . Marionette && Backbone . Marionette . TemplateCache && ! isMarionetteInitialized ) { originalClearCache = Backbone . Marionette . TemplateCache . clear ; // Custom implementation of Marionette.TemplateCache.clear() // // When the Marionette cache is cleared, the DeclarativeViews cache is cleared as well. This is not technically // necessary, but makes sense. If there is a reason to invalidate a cached template, it applies to all caches. Backbone . Marionette . TemplateCache . clear = function ( ) { if ( arguments . length ) { Backbone . DeclarativeViews . clearCachedTemplate ( arguments , true ) ; } else { Backbone . DeclarativeViews . clearCache ( true ) ; } originalClearCache . apply ( this , arguments ) ; } ; isMarionetteInitialized = true ; // Removed: integration of the Marionette and Backbone.Declarative.Views template loading mechanisms // // Integrating the template loaders turned out to be of little or no benefit, and could potentially have caused // problems with other custom loaders. In detail: // // - Integration saved exactly one DOM access per *template*. Given the limited number of templates in a project, //   the performance gain had often been too small to even be measurable. // // - During testing with just a single template, the net effect was even negative (!) - integration and the //   associated overhead seemed to slow things down. // // - With integration, custom loaders like the one for Marionette/Handlebars had been trickier to use. Load //   order suddenly mattered. The code setting up a custom loader had to be run after integrating //   Backbone.Declarative.Views with Marionette. Otherwise, the custom loader would haven been overwritten, //   breaking the application. // // In a nutshell, loader integration has proven to be more trouble than it is worth. } }


Input: Creates and returns a custom error type . [CODESPLIT] function createCustomErrorType ( name ) { function CustomError ( message ) { this . message = message ; if ( Error . captureStackTrace ) { Error . captureStackTrace ( this , this . constructor ) ; } else { this . stack = ( new Error ( ) ) . stack ; } } CustomError . prototype = new Error ( ) ; CustomError . prototype . name = name ; CustomError . prototype . constructor = CustomError ; return CustomError ; }


Input: Get the currently registered handler for the specified name . Throws an exception if no handler is found . [CODESPLIT] function ( name ) { var config = this . _wreqrHandlers [ name ] ; if ( ! config ) { return ; } return function ( ) { return config . callback . apply ( config . context , arguments ) ; } ; }


Input: Execute a named command with the supplied args [CODESPLIT] function ( name ) { name = arguments [ 0 ] ; var args = _ . rest ( arguments ) ; if ( this . hasHandler ( name ) ) { this . getHandler ( name ) . apply ( this , args ) ; } else { this . storage . addCommand ( name , args ) ; } }


Input: Attach the handlers to a given message system type [CODESPLIT] function ( type , hash , context ) { if ( ! hash ) { return ; } context = context || this ; var method = type === "vent" ? "on" : "setHandler" ; _ . each ( hash , function ( fn , eventName ) { this [ type ] [ method ] ( eventName , _ . bind ( fn , context ) ) ; } , this ) ; }


Input: Trigger the dom : refresh event and corresponding onDomRefresh method [CODESPLIT] function triggerDOMRefresh ( ) { if ( view . _isShown && view . _isRendered && Marionette . isNodeAttached ( view . el ) ) { Marionette . triggerMethodOn ( view , 'dom:refresh' , view ) ; } }


Input: generic looping function [CODESPLIT] function iterateEvents ( target , entity , bindings , functionCallback , stringCallback ) { if ( ! entity || ! bindings ) { return ; } // type-check bindings if ( ! _ . isObject ( bindings ) ) { throw new Marionette . Error ( { message : 'Bindings must be an object or function.' , url : 'marionette.functions.html#marionettebindentityevents' } ) ; } // allow the bindings to be a function bindings = Marionette . _getValue ( bindings , target ) ; // iterate the bindings and bind them _ . each ( bindings , function ( methods , evt ) { // allow for a function as the handler, // or a list of event names as a string if ( _ . isFunction ( methods ) ) { functionCallback ( target , entity , evt , methods ) ; } else { stringCallback ( target , entity , evt , methods ) ; } } ) ; }


Input: Add a callback to be executed . Callbacks added here are guaranteed to execute even if they are added after the run method is called . [CODESPLIT] function ( callback , contextOverride ) { var promise = _ . result ( this . _deferred , 'promise' ) ; this . _callbacks . push ( { cb : callback , ctx : contextOverride } ) ; promise . then ( function ( args ) { if ( contextOverride ) { args . context = contextOverride ; } callback . call ( args . context , args . options ) ; } ) ; }


Input: Displays a backbone view instance inside of the region . Handles calling the render method for you . Reads content directly from the el attribute . Also calls an optional onShow and onDestroy method on your view just after showing or just before destroying the view respectively . The preventDestroy option can be used to prevent a view from the old view being destroyed on show . The forceShow option can be used to force a view to be re - rendered if it s already shown in the region . [CODESPLIT] function ( view , options ) { if ( ! this . _ensureElement ( ) ) { return ; } this . _ensureViewIsIntact ( view ) ; Marionette . MonitorDOMRefresh ( view ) ; var showOptions = options || { } ; var isDifferentView = view !== this . currentView ; var preventDestroy = ! ! showOptions . preventDestroy ; var forceShow = ! ! showOptions . forceShow ; // We are only changing the view if there is a current view to change to begin with var isChangingView = ! ! this . currentView ; // Only destroy the current view if we don't want to `preventDestroy` and if // the view given in the first argument is different than `currentView` var _shouldDestroyView = isDifferentView && ! preventDestroy ; // Only show the view given in the first argument if it is different than // the current view or if we want to re-show the view. Note that if // `_shouldDestroyView` is true, then `_shouldShowView` is also necessarily true. var _shouldShowView = isDifferentView || forceShow ; if ( isChangingView ) { this . triggerMethod ( 'before:swapOut' , this . currentView , this , options ) ; } if ( this . currentView && isDifferentView ) { delete this . currentView . _parent ; } if ( _shouldDestroyView ) { this . empty ( ) ; // A `destroy` event is attached to the clean up manually removed views. // We need to detach this event when a new view is going to be shown as it // is no longer relevant. } else if ( isChangingView && _shouldShowView ) { this . currentView . off ( 'destroy' , this . empty , this ) ; } if ( _shouldShowView ) { // We need to listen for if a view is destroyed // in a way other than through the region. // If this happens we need to remove the reference // to the currentView since once a view has been destroyed // we can not reuse it. view . once ( 'destroy' , this . empty , this ) ; // make this region the view's parent, // It's important that this parent binding happens before rendering // so that any events the child may trigger during render can also be // triggered on the child's ancestor views view . _parent = this ; this . _renderView ( view ) ; if ( isChangingView ) { this . triggerMethod ( 'before:swap' , view , this , options ) ; } this . triggerMethod ( 'before:show' , view , this , options ) ; Marionette . triggerMethodOn ( view , 'before:show' , view , this , options ) ; if ( isChangingView ) { this . triggerMethod ( 'swapOut' , this . currentView , this , options ) ; } // An array of views that we're about to display var attachedRegion = Marionette . isNodeAttached ( this . el ) ; // The views that we're about to attach to the document // It's important that we prevent _getNestedViews from being executed unnecessarily // as it's a potentially-slow method var displayedViews = [ ] ; var attachOptions = _ . extend ( { triggerBeforeAttach : this . triggerBeforeAttach , triggerAttach : this . triggerAttach } , showOptions ) ; if ( attachedRegion && attachOptions . triggerBeforeAttach ) { displayedViews = this . _displayedViews ( view ) ; this . _triggerAttach ( displayedViews , 'before:' ) ; } this . attachHtml ( view ) ; this . currentView = view ; if ( attachedRegion && attachOptions . triggerAttach ) { displayedViews = this . _displayedViews ( view ) ; this . _triggerAttach ( displayedViews ) ; } if ( isChangingView ) { this . triggerMethod ( 'swap' , view , this , options ) ; } this . triggerMethod ( 'show' , view , this , options ) ; Marionette . triggerMethodOn ( view , 'show' , view , this , options ) ; return this ; } return this ; }


Input: Destroy the current view if there is one . If there is no current view it does nothing and returns immediately . [CODESPLIT] function ( options ) { var view = this . currentView ; var emptyOptions = options || { } ; var preventDestroy = ! ! emptyOptions . preventDestroy ; // If there is no view in the region // we should not remove anything if ( ! view ) { return this ; } view . off ( 'destroy' , this . empty , this ) ; this . triggerMethod ( 'before:empty' , view ) ; if ( ! preventDestroy ) { this . _destroyView ( ) ; } this . triggerMethod ( 'empty' , view ) ; // Remove region pointer to the currentView delete this . currentView ; if ( preventDestroy ) { this . $el . contents ( ) . detach ( ) ; } return this ; }


Input: call destroy or remove depending on which is found on the view ( if showing a raw Backbone view or a Marionette View ) [CODESPLIT] function ( ) { var view = this . currentView ; if ( view . isDestroyed ) { return ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'before:destroy' , view ) ; } if ( view . destroy ) { view . destroy ( ) ; } else { view . remove ( ) ; // appending isDestroyed to raw Backbone View allows regions // to throw a ViewDestroyedError for this view view . isDestroyed = true ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'destroy' , view ) ; } }


Input: Build an instance of a region by passing in a configuration object and a default region class to use if none is specified in the config . The config object should either be a string as a jQuery DOM selector a Region class directly or an object literal that specifies a selector a custom regionClass and any options to be supplied to the region : js { selector : #foo regionClass : MyCustomRegion allowMissingEl : false } [CODESPLIT] function ( regionConfig , DefaultRegionClass ) { if ( _ . isString ( regionConfig ) ) { return this . _buildRegionFromSelector ( regionConfig , DefaultRegionClass ) ; } if ( regionConfig . selector || regionConfig . el || regionConfig . regionClass ) { return this . _buildRegionFromObject ( regionConfig , DefaultRegionClass ) ; } if ( _ . isFunction ( regionConfig ) ) { return this . _buildRegionFromRegionClass ( regionConfig ) ; } throw new Marionette . Error ( { message : 'Improper region configuration type.' , url : 'marionette.region.html#region-configuration-types' } ) ; }


Input: Build the region from a configuration object js { selector : #foo regionClass : FooRegion allowMissingEl : false } [CODESPLIT] function ( regionConfig , DefaultRegionClass ) { var RegionClass = regionConfig . regionClass || DefaultRegionClass ; var options = _ . omit ( regionConfig , 'selector' , 'regionClass' ) ; if ( regionConfig . selector && ! options . el ) { options . el = regionConfig . selector ; } return new RegionClass ( options ) ; }


Input: Add multiple regions using an object literal or a function that returns an object literal where each key becomes the region name and each value is the region definition . [CODESPLIT] function ( regionDefinitions , defaults ) { regionDefinitions = Marionette . _getValue ( regionDefinitions , this , arguments ) ; return _ . reduce ( regionDefinitions , function ( regions , definition , name ) { if ( _ . isString ( definition ) ) { definition = { selector : definition } ; } if ( definition . selector ) { definition = _ . defaults ( { } , definition , defaults ) ; } regions [ name ] = this . addRegion ( name , definition ) ; return regions ; } , { } , this ) ; }


Input: Add an individual region to the region manager and return the region instance [CODESPLIT] function ( name , definition ) { var region ; if ( definition instanceof Marionette . Region ) { region = definition ; } else { region = Marionette . Region . buildRegion ( definition , Marionette . Region ) ; } this . triggerMethod ( 'before:add:region' , name , region ) ; region . _parent = this ; this . _store ( name , region ) ; this . triggerMethod ( 'add:region' , name , region ) ; return region ; }


Input: Empty all regions in the region manager and remove them [CODESPLIT] function ( ) { var regions = this . getRegions ( ) ; _ . each ( this . _regions , function ( region , name ) { this . _remove ( name , region ) ; } , this ) ; return regions ; }


Input: internal method to remove a region [CODESPLIT] function ( name , region ) { this . triggerMethod ( 'before:remove:region' , name , region ) ; region . empty ( ) ; region . stopListening ( ) ; delete region . _parent ; delete this . _regions [ name ] ; this . length -- ; this . triggerMethod ( 'remove:region' , name , region ) ; }


Input: Get the specified template by id . Either retrieves the cached version or loads it from the DOM . [CODESPLIT] function ( templateId , options ) { var cachedTemplate = this . templateCaches [ templateId ] ; if ( ! cachedTemplate ) { cachedTemplate = new Marionette . TemplateCache ( templateId ) ; this . templateCaches [ templateId ] = cachedTemplate ; } return cachedTemplate . load ( options ) ; }


Input: Clear templates from the cache . If no arguments are specified clears all templates : clear () If arguments are specified clears each of the specified templates from the cache : clear ( #t1 #t2 ... ) [CODESPLIT] function ( ) { var i ; var args = _ . toArray ( arguments ) ; var length = args . length ; if ( length > 0 ) { for ( i = 0 ; i < length ; i ++ ) { delete this . templateCaches [ args [ i ] ] ; } } else { this . templateCaches = { } ; } }


Input: Internal method to load the template [CODESPLIT] function ( options ) { // Guard clause to prevent loading this template more than once if ( this . compiledTemplate ) { return this . compiledTemplate ; } // Load the template and compile it var template = this . loadTemplate ( this . templateId , options ) ; this . compiledTemplate = this . compileTemplate ( template , options ) ; return this . compiledTemplate ; }


Input: Load a template from the DOM by default . Override this method to provide your own template retrieval For asynchronous loading with AMD / RequireJS consider using a template - loader plugin as described here : https : // github . com / marionettejs / backbone . marionette / wiki / Using - marionette - with - requirejs [CODESPLIT] function ( templateId , options ) { var $template = Backbone . $ ( templateId ) ; if ( ! $template . length ) { throw new Marionette . Error ( { name : 'NoTemplateError' , message : 'Could not find template: "' + templateId + '"' } ) ; } return $template . html ( ) ; }


Input: Render a template with data . The template parameter is passed to the TemplateCache object to retrieve the template function . Override this method to provide your own custom rendering and template handling for all of Marionette . [CODESPLIT] function ( template , data ) { if ( ! template ) { throw new Marionette . Error ( { name : 'TemplateNotFoundError' , message : 'Cannot render the template since its false, null or undefined.' } ) ; } var templateFunc = _ . isFunction ( template ) ? template : Marionette . TemplateCache . get ( template ) ; return templateFunc ( data ) ; }


Input: Mix in template helper methods . Looks for a templateHelpers attribute which can either be an object literal or a function that returns an object literal . All methods and attributes from this object are copies to the object passed in . [CODESPLIT] function ( target ) { target = target || { } ; var templateHelpers = this . getOption ( 'templateHelpers' ) ; templateHelpers = Marionette . _getValue ( templateHelpers , this ) ; return _ . extend ( target , templateHelpers ) ; }


Input: normalize the keys of passed hash with the views ui selectors . { [CODESPLIT] function ( hash ) { var uiBindings = _ . result ( this , '_uiBindings' ) ; return Marionette . normalizeUIKeys ( hash , uiBindings || _ . result ( this , 'ui' ) ) ; }


Input: normalize the values of passed hash with the views ui selectors . { foo : [CODESPLIT] function ( hash , properties ) { var ui = _ . result ( this , 'ui' ) ; var uiBindings = _ . result ( this , '_uiBindings' ) ; return Marionette . normalizeUIValues ( hash , uiBindings || ui , properties ) ; }


Input: Configure triggers to forward DOM events to view events . triggers : { click . foo : do : foo } [CODESPLIT] function ( ) { if ( ! this . triggers ) { return ; } // Allow `triggers` to be configured as a function var triggers = this . normalizeUIKeys ( _ . result ( this , 'triggers' ) ) ; // Configure the triggers, prevent default // action and stop propagation of DOM events return _ . reduce ( triggers , function ( events , value , key ) { events [ key ] = this . _buildViewTrigger ( value ) ; return events ; } , { } , this ) ; }


Input: Overriding Backbone . View s delegateEvents to handle the triggers modelEvents and collectionEvents configuration [CODESPLIT] function ( events ) { this . _delegateDOMEvents ( events ) ; this . bindEntityEvents ( this . model , this . getOption ( 'modelEvents' ) ) ; this . bindEntityEvents ( this . collection , this . getOption ( 'collectionEvents' ) ) ; _ . each ( this . _behaviors , function ( behavior ) { behavior . bindEntityEvents ( this . model , behavior . getOption ( 'modelEvents' ) ) ; behavior . bindEntityEvents ( this . collection , behavior . getOption ( 'collectionEvents' ) ) ; } , this ) ; return this ; }


Input: internal method to delegate DOM events and triggers [CODESPLIT] function ( eventsArg ) { var events = Marionette . _getValue ( eventsArg || this . events , this ) ; // normalize ui keys events = this . normalizeUIKeys ( events ) ; if ( _ . isUndefined ( eventsArg ) ) { this . events = events ; } var combinedEvents = { } ; // look up if this view has behavior events var behaviorEvents = _ . result ( this , 'behaviorEvents' ) || { } ; var triggers = this . configureTriggers ( ) ; var behaviorTriggers = _ . result ( this , 'behaviorTriggers' ) || { } ; // behavior events will be overriden by view events and or triggers _ . extend ( combinedEvents , behaviorEvents , events , triggers , behaviorTriggers ) ; Backbone . View . prototype . delegateEvents . call ( this , combinedEvents ) ; }


Input: Overriding Backbone . View s undelegateEvents to handle unbinding the triggers modelEvents and collectionEvents config [CODESPLIT] function ( ) { Backbone . View . prototype . undelegateEvents . apply ( this , arguments ) ; this . unbindEntityEvents ( this . model , this . getOption ( 'modelEvents' ) ) ; this . unbindEntityEvents ( this . collection , this . getOption ( 'collectionEvents' ) ) ; _ . each ( this . _behaviors , function ( behavior ) { behavior . unbindEntityEvents ( this . model , behavior . getOption ( 'modelEvents' ) ) ; behavior . unbindEntityEvents ( this . collection , behavior . getOption ( 'collectionEvents' ) ) ; } , this ) ; return this ; }


Input: Default destroy implementation for removing a view from the DOM and unbinding it . Regions will call this method for you . You can specify an onDestroy method in your view to add custom code that is called after the view is destroyed . [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } var args = _ . toArray ( arguments ) ; this . triggerMethod . apply ( this , [ 'before:destroy' ] . concat ( args ) ) ; // mark as destroyed before doing the actual destroy, to // prevent infinite loops within "destroy" event handlers // that are trying to destroy other views this . isDestroyed = true ; this . triggerMethod . apply ( this , [ 'destroy' ] . concat ( args ) ) ; // unbind UI elements this . unbindUIElements ( ) ; this . isRendered = false ; // remove the view from the DOM this . remove ( ) ; // Call destroy on each behavior after // destroying the view. // This unbinds event listeners // that behaviors have registered for. _ . invoke ( this . _behaviors , 'destroy' , args ) ; return this ; }


Input: This method binds the elements specified in the ui hash inside the view s code with the associated jQuery selectors . [CODESPLIT] function ( ) { if ( ! this . ui ) { return ; } // store the ui hash in _uiBindings so they can be reset later // and so re-rendering the view will be able to find the bindings if ( ! this . _uiBindings ) { this . _uiBindings = this . ui ; } // get the bindings result, as a function or otherwise var bindings = _ . result ( this , '_uiBindings' ) ; // empty the ui so we don't have anything to start with this . ui = { } ; // bind each of the selectors _ . each ( bindings , function ( selector , key ) { this . ui [ key ] = this . $ ( selector ) ; } , this ) ; }


Input: Internal method to create an event handler for a given triggerDef like click : foo [CODESPLIT] function ( triggerDef ) { var options = _ . defaults ( { } , triggerDef , { preventDefault : true , stopPropagation : true } ) ; var eventName = _ . isObject ( triggerDef ) ? options . event : triggerDef ; return function ( e ) { if ( e ) { if ( e . preventDefault && options . preventDefault ) { e . preventDefault ( ) ; } if ( e . stopPropagation && options . stopPropagation ) { e . stopPropagation ( ) ; } } var args = { view : this , model : this . model , collection : this . collection } ; this . triggerMethod ( eventName , args ) ; } ; }


Input: import the triggerMethod to trigger events with corresponding methods if the method exists [CODESPLIT] function ( ) { var ret = Marionette . _triggerMethod ( this , arguments ) ; this . _triggerEventOnBehaviors ( arguments ) ; this . _triggerEventOnParentLayout ( arguments [ 0 ] , _ . rest ( arguments ) ) ; return ret ; }


Input: Returns an array of every nested view within this view [CODESPLIT] function ( ) { var children = this . _getImmediateChildren ( ) ; if ( ! children . length ) { return children ; } return _ . reduce ( children , function ( memo , view ) { if ( ! view . _getNestedViews ) { return memo ; } return memo . concat ( view . _getNestedViews ( ) ) ; } , children ) ; }


Input: Walk the _parent tree until we find a layout view ( if one exists ) . Returns the parent layout view hierarchically closest to this view . [CODESPLIT] function ( ) { var parent = this . _parent ; while ( parent ) { if ( parent instanceof Marionette . LayoutView ) { return parent ; } parent = parent . _parent ; } }


Input: Serialize the model or collection for the view . If a model is found the view s serializeModel is called . If a collection is found each model in the collection is serialized by calling the view s serializeCollection and put into an items array in the resulting data . If both are found defaults to the model . You can override the serializeData method in your own view definition to provide custom serialization for your view s data . [CODESPLIT] function ( ) { if ( ! this . model && ! this . collection ) { return { } ; } var args = [ this . model || this . collection ] ; if ( arguments . length ) { args . push . apply ( args , arguments ) ; } if ( this . model ) { return this . serializeModel . apply ( this , args ) ; } else { return { items : this . serializeCollection . apply ( this , args ) } ; } }


Input: Internal method to render the template with the serialized data and template helpers via the Marionette . Renderer object . Throws an UndefinedTemplateError error if the template is any falsely value but literal false . [CODESPLIT] function ( ) { var template = this . getTemplate ( ) ; // Allow template-less item views if ( template === false ) { return ; } if ( ! template ) { throw new Marionette . Error ( { name : 'UndefinedTemplateError' , message : 'Cannot render the template since it is null or undefined.' } ) ; } // Add in entity data and template helpers var data = this . mixinTemplateHelpers ( this . serializeData ( ) ) ; // Render and add to el var html = Marionette . Renderer . render ( template , data , this ) ; this . attachElContent ( html ) ; return this ; }


Input: constructor option to pass { sort : false } to prevent the CollectionView from maintaining the sorted order of the collection . This will fallback onto appending childView s to the end . option to pass { comparator : compFunction () } to allow the CollectionView to use a custom sort order for the collection . [CODESPLIT] function ( options ) { this . once ( 'render' , this . _initialEvents ) ; this . _initChildViewStorage ( ) ; Marionette . View . apply ( this , arguments ) ; this . on ( { 'before:show' : this . _onBeforeShowCalled , 'show' : this . _onShowCalled , 'before:attach' : this . _onBeforeAttachCalled , 'attach' : this . _onAttachCalled } ) ; this . initRenderBuffer ( ) ; }


Input: Configured the initial events that the collection view binds to . [CODESPLIT] function ( ) { if ( this . collection ) { this . listenTo ( this . collection , 'add' , this . _onCollectionAdd ) ; this . listenTo ( this . collection , 'remove' , this . _onCollectionRemove ) ; this . listenTo ( this . collection , 'reset' , this . render ) ; if ( this . getOption ( 'sort' ) ) { this . listenTo ( this . collection , 'sort' , this . _sortViews ) ; } } }


Input: Handle a child added to the collection [CODESPLIT] function ( child , collection , opts ) { // `index` is present when adding with `at` since BB 1.2; indexOf fallback for < 1.2 var index = opts . at !== undefined && ( opts . index || collection . indexOf ( child ) ) ; // When filtered or when there is no initial index, calculate index. if ( this . getOption ( 'filter' ) || index === false ) { index = _ . indexOf ( this . _filteredSortedModels ( index ) , child ) ; } if ( this . _shouldAddChild ( child , index ) ) { this . destroyEmptyView ( ) ; var ChildView = this . getChildView ( child ) ; this . addChild ( child , ChildView , index ) ; } }


Input: Reorder DOM after sorting . When your element s rendering do not use their index you can pass reorderOnSort : true to only reorder the DOM after a sort instead of rendering all the collectionView [CODESPLIT] function ( ) { var children = this . children ; var models = this . _filteredSortedModels ( ) ; if ( ! models . length && this . _showingEmptyView ) { return this ; } var anyModelsAdded = _ . some ( models , function ( model ) { return ! children . findByModel ( model ) ; } ) ; // If there are any new models added due to filtering // We need to add child views // So render as normal if ( anyModelsAdded ) { this . render ( ) ; } else { // get the DOM nodes in the same order as the models var elsToReorder = _ . map ( models , function ( model , index ) { var view = children . findByModel ( model ) ; view . _index = index ; return view . el ; } ) ; // find the views that were children before but arent in this new ordering var filteredOutViews = children . filter ( function ( view ) { return ! _ . contains ( elsToReorder , view . el ) ; } ) ; this . triggerMethod ( 'before:reorder' ) ; // since append moves elements that are already in the DOM, // appending the elements will effectively reorder them this . _appendReorderedChildren ( elsToReorder ) ; // remove any views that have been filtered out _ . each ( filteredOutViews , this . removeChildView , this ) ; this . checkEmpty ( ) ; this . triggerMethod ( 'reorder' ) ; } }


Input: Internal method . This checks for any changes in the order of the collection . If the index of any view doesn t match it will render . [CODESPLIT] function ( ) { var models = this . _filteredSortedModels ( ) ; // check for any changes in sort order of views var orderChanged = _ . find ( models , function ( item , index ) { var view = this . children . findByModel ( item ) ; return ! view || view . _index !== index ; } , this ) ; if ( orderChanged ) { this . resortView ( ) ; } }


Input: Internal method . Separated so that CompositeView can have more control over events being triggered around the rendering process [CODESPLIT] function ( ) { this . destroyEmptyView ( ) ; this . destroyChildren ( { checkEmpty : false } ) ; if ( this . isEmpty ( this . collection ) ) { this . showEmptyView ( ) ; } else { this . triggerMethod ( 'before:render:collection' , this ) ; this . startBuffering ( ) ; this . showCollection ( ) ; this . endBuffering ( ) ; this . triggerMethod ( 'render:collection' , this ) ; // If we have shown children and none have passed the filter, show the empty view if ( this . children . isEmpty ( ) && this . getOption ( 'filter' ) ) { this . showEmptyView ( ) ; } } }


Input: Internal method to loop through collection and show each child view . [CODESPLIT] function ( ) { var ChildView ; var models = this . _filteredSortedModels ( ) ; _ . each ( models , function ( child , index ) { ChildView = this . getChildView ( child ) ; this . addChild ( child , ChildView , index ) ; } , this ) ; }


Input: Allow the collection to be sorted by a custom view comparator [CODESPLIT] function ( addedAt ) { var viewComparator = this . getViewComparator ( ) ; var models = this . collection . models ; addedAt = Math . min ( Math . max ( addedAt , 0 ) , models . length - 1 ) ; if ( viewComparator ) { var addedModel ; // Preserve `at` location, even for a sorted view if ( addedAt ) { addedModel = models [ addedAt ] ; models = models . slice ( 0 , addedAt ) . concat ( models . slice ( addedAt + 1 ) ) ; } models = this . _sortModelsBy ( models , viewComparator ) ; if ( addedModel ) { models . splice ( addedAt , 0 , addedModel ) ; } } // Filter after sorting in case the filter uses the index if ( this . getOption ( 'filter' ) ) { models = _ . filter ( models , function ( model , index ) { return this . _shouldAddChild ( model , index ) ; } , this ) ; } return models ; }


Input: Internal method to show an empty view in place of a collection of child views when the collection is empty [CODESPLIT] function ( ) { var EmptyView = this . getEmptyView ( ) ; if ( EmptyView && ! this . _showingEmptyView ) { this . triggerMethod ( 'before:render:empty' ) ; this . _showingEmptyView = true ; var model = new Backbone . Model ( ) ; this . addEmptyView ( model , EmptyView ) ; this . triggerMethod ( 'render:empty' ) ; } }


Input: Render and show the emptyView . Similar to addChild method but add : child events are not fired and the event from emptyView are not forwarded [CODESPLIT] function ( child , EmptyView ) { // Only trigger attach if already shown, attached, and not buffering, otherwise endBuffer() or // Region#show() handles this. var canTriggerAttach = this . _isShown && ! this . isBuffering && Marionette . isNodeAttached ( this . el ) ; var nestedViews ; // get the emptyViewOptions, falling back to childViewOptions var emptyViewOptions = this . getOption ( 'emptyViewOptions' ) || this . getOption ( 'childViewOptions' ) ; if ( _ . isFunction ( emptyViewOptions ) ) { emptyViewOptions = emptyViewOptions . call ( this , child , this . _emptyViewIndex ) ; } // build the empty view var view = this . buildChildView ( child , EmptyView , emptyViewOptions ) ; view . _parent = this ; // Proxy emptyView events this . proxyChildEvents ( view ) ; view . once ( 'render' , function ( ) { // trigger the 'before:show' event on `view` if the collection view has already been shown if ( this . _isShown ) { Marionette . triggerMethodOn ( view , 'before:show' , view ) ; } // Trigger `before:attach` following `render` to avoid adding logic and event triggers // to public method `renderChildView()`. if ( canTriggerAttach && this . _triggerBeforeAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'before:attach' ) ; } } , this ) ; // Store the `emptyView` like a `childView` so we can properly remove and/or close it later this . children . add ( view ) ; this . renderChildView ( view , this . _emptyViewIndex ) ; // Trigger `attach` if ( canTriggerAttach && this . _triggerAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'attach' ) ; } // call the 'show' method if the collection view has already been shown if ( this . _isShown ) { Marionette . triggerMethodOn ( view , 'show' , view ) ; } }


Input: Render the child s view and add it to the HTML for the collection view at a given index . This will also update the indices of later views in the collection in order to keep the children in sync with the collection . [CODESPLIT] function ( child , ChildView , index ) { var childViewOptions = this . getOption ( 'childViewOptions' ) ; childViewOptions = Marionette . _getValue ( childViewOptions , this , [ child , index ] ) ; var view = this . buildChildView ( child , ChildView , childViewOptions ) ; // increment indices of views after this one this . _updateIndices ( view , true , index ) ; this . triggerMethod ( 'before:add:child' , view ) ; this . _addChildView ( view , index ) ; this . triggerMethod ( 'add:child' , view ) ; view . _parent = this ; return view ; }


Input: Internal method . This decrements or increments the indices of views after the added / removed view to keep in sync with the collection . [CODESPLIT] function ( view , increment , index ) { if ( ! this . getOption ( 'sort' ) ) { return ; } if ( increment ) { // assign the index to the view view . _index = index ; } // update the indexes of views after this one this . children . each ( function ( laterView ) { if ( laterView . _index >= view . _index ) { laterView . _index += increment ? 1 : - 1 ; } } ) ; }


Input: Internal Method . Add the view to children and render it at the given index . [CODESPLIT] function ( view , index ) { // Only trigger attach if already shown, attached, and not buffering, otherwise endBuffer() or // Region#show() handles this. var canTriggerAttach = this . _isShown && ! this . isBuffering && Marionette . isNodeAttached ( this . el ) ; var nestedViews ; // set up the child view event forwarding this . proxyChildEvents ( view ) ; view . once ( 'render' , function ( ) { // trigger the 'before:show' event on `view` if the collection view has already been shown if ( this . _isShown && ! this . isBuffering ) { Marionette . triggerMethodOn ( view , 'before:show' , view ) ; } // Trigger `before:attach` following `render` to avoid adding logic and event triggers // to public method `renderChildView()`. if ( canTriggerAttach && this . _triggerBeforeAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'before:attach' ) ; } } , this ) ; // Store the child view itself so we can properly remove and/or destroy it later this . children . add ( view ) ; this . renderChildView ( view , index ) ; // Trigger `attach` if ( canTriggerAttach && this . _triggerAttach ) { nestedViews = this . _getViewAndNested ( view ) ; this . _triggerMethodMany ( nestedViews , this , 'attach' ) ; } // Trigger `show` if ( this . _isShown && ! this . isBuffering ) { Marionette . triggerMethodOn ( view , 'show' , view ) ; } }


Input: render the child view [CODESPLIT] function ( view , index ) { if ( ! view . supportsRenderLifecycle ) { Marionette . triggerMethodOn ( view , 'before:render' , view ) ; } view . render ( ) ; if ( ! view . supportsRenderLifecycle ) { Marionette . triggerMethodOn ( view , 'render' , view ) ; } this . attachHtml ( this , view , index ) ; return view ; }


Input: Build a childView for a model in the collection . [CODESPLIT] function ( child , ChildViewClass , childViewOptions ) { var options = _ . extend ( { model : child } , childViewOptions ) ; var childView = new ChildViewClass ( options ) ; Marionette . MonitorDOMRefresh ( childView ) ; return childView ; }


Input: Remove the child view and destroy it . This function also updates the indices of later views in the collection in order to keep the children in sync with the collection . [CODESPLIT] function ( view ) { if ( ! view ) { return view ; } this . triggerMethod ( 'before:remove:child' , view ) ; if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'before:destroy' , view ) ; } // call 'destroy' or 'remove', depending on which is found if ( view . destroy ) { view . destroy ( ) ; } else { view . remove ( ) ; } if ( ! view . supportsDestroyLifecycle ) { Marionette . triggerMethodOn ( view , 'destroy' , view ) ; } delete view . _parent ; this . stopListening ( view ) ; this . children . remove ( view ) ; this . triggerMethod ( 'remove:child' , view ) ; // decrement the index of views after this one this . _updateIndices ( view , false ) ; return view ; }


Input: Create a fragment buffer from the currently buffered children [CODESPLIT] function ( ) { var elBuffer = document . createDocumentFragment ( ) ; _ . each ( this . _bufferedChildren , function ( b ) { elBuffer . appendChild ( b . el ) ; } ) ; return elBuffer ; }


Input: Append the HTML to the collection s el . Override this method to do something other than . append . [CODESPLIT] function ( collectionView , childView , index ) { if ( collectionView . isBuffering ) { // buffering happens on reset events and initial renders // in order to reduce the number of inserts into the // document, which are expensive. collectionView . _bufferedChildren . splice ( index , 0 , childView ) ; } else { // If we've already rendered the main collection, append // the new child into the correct order if we need to. Otherwise // append to the end. if ( ! collectionView . _insertBefore ( childView , index ) ) { collectionView . _insertAfter ( childView ) ; } } }


Input: Internal method . Check whether we need to insert the view into the correct position . [CODESPLIT] function ( childView , index ) { var currentView ; var findPosition = this . getOption ( 'sort' ) && ( index < this . children . length - 1 ) ; if ( findPosition ) { // Find the view after this one currentView = this . children . find ( function ( view ) { return view . _index === index + 1 ; } ) ; } if ( currentView ) { currentView . $el . before ( childView . el ) ; return true ; } return false ; }


Input: Handle cleanup and other destroying needs for the collection of views [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } this . triggerMethod ( 'before:destroy:collection' ) ; this . destroyChildren ( { checkEmpty : false } ) ; this . triggerMethod ( 'destroy:collection' ) ; return Marionette . View . prototype . destroy . apply ( this , arguments ) ; }


Input: Destroy the child views that this collection view is holding on to if any [CODESPLIT] function ( options ) { var destroyOptions = options || { } ; var shouldCheckEmpty = true ; var childViews = this . children . map ( _ . identity ) ; if ( ! _ . isUndefined ( destroyOptions . checkEmpty ) ) { shouldCheckEmpty = destroyOptions . checkEmpty ; } this . children . each ( this . removeChildView , this ) ; if ( shouldCheckEmpty ) { this . checkEmpty ( ) ; } return childViews ; }


Input: Return true if the given child should be shown Return false otherwise The filter will be passed ( child index collection ) Where child is the given model index is the index of that model in the collection collection is the collection referenced by this CollectionView [CODESPLIT] function ( child , index ) { var filter = this . getOption ( 'filter' ) ; return ! _ . isFunction ( filter ) || filter . call ( this , child , index , this . collection ) ; }


Input: Set up the child view event forwarding . Uses a childview : prefix in front of all forwarded events . [CODESPLIT] function ( view ) { var prefix = this . getOption ( 'childViewEventPrefix' ) ; // Forward all child view events through the parent, // prepending "childview:" to the event name this . listenTo ( view , 'all' , function ( ) { var args = _ . toArray ( arguments ) ; var rootEvent = args [ 0 ] ; var childEvents = this . normalizeMethods ( _ . result ( this , 'childEvents' ) ) ; args [ 0 ] = prefix + ':' + rootEvent ; args . splice ( 1 , 0 , view ) ; // call collectionView childEvent if defined if ( typeof childEvents !== 'undefined' && _ . isFunction ( childEvents [ rootEvent ] ) ) { childEvents [ rootEvent ] . apply ( this , args . slice ( 1 ) ) ; } this . triggerMethod . apply ( this , args ) ; } ) ; }


Input: Configured the initial events that the composite view binds to . Override this method to prevent the initial events or to add your own initial events . [CODESPLIT] function ( ) { // Bind only after composite view is rendered to avoid adding child views // to nonexistent childViewContainer if ( this . collection ) { this . listenTo ( this . collection , 'add' , this . _onCollectionAdd ) ; this . listenTo ( this . collection , 'remove' , this . _onCollectionRemove ) ; this . listenTo ( this . collection , 'reset' , this . _renderChildren ) ; if ( this . getOption ( 'sort' ) ) { this . listenTo ( this . collection , 'sort' , this . _sortViews ) ; } } }


Input: Serialize the model for the view . You can override the serializeData method in your own view definition to provide custom serialization for your view s data . [CODESPLIT] function ( ) { var data = { } ; if ( this . model ) { data = _ . partial ( this . serializeModel , this . model ) . apply ( this , arguments ) ; } return data ; }


Input: Renders the model and the collection . [CODESPLIT] function ( ) { this . _ensureViewIsIntact ( ) ; this . _isRendering = true ; this . resetChildViewContainer ( ) ; this . triggerMethod ( 'before:render' , this ) ; this . _renderTemplate ( ) ; this . _renderChildren ( ) ; this . _isRendering = false ; this . isRendered = true ; this . triggerMethod ( 'render' , this ) ; return this ; }


Input: Render the root template that the children views are appended to [CODESPLIT] function ( ) { var data = { } ; data = this . serializeData ( ) ; data = this . mixinTemplateHelpers ( data ) ; this . triggerMethod ( 'before:render:template' ) ; var template = this . getTemplate ( ) ; var html = Marionette . Renderer . render ( template , data , this ) ; this . attachElContent ( html ) ; // the ui bindings is done here and not at the end of render since they // will not be available until after the model is rendered, but should be // available before the collection is rendered. this . bindUIElements ( ) ; this . triggerMethod ( 'render:template' ) ; }


Input: Internal method to ensure an $childViewContainer exists for the attachHtml method to use . [CODESPLIT] function ( containerView , childView ) { if ( ! ! containerView . $childViewContainer ) { return containerView . $childViewContainer ; } var container ; var childViewContainer = Marionette . getOption ( containerView , 'childViewContainer' ) ; if ( childViewContainer ) { var selector = Marionette . _getValue ( childViewContainer , containerView ) ; if ( selector . charAt ( 0 ) === '@' && containerView . ui ) { container = containerView . ui [ selector . substr ( 4 ) ] ; } else { container = containerView . $ ( selector ) ; } if ( container . length <= 0 ) { throw new Marionette . Error ( { name : 'ChildViewContainerMissingError' , message : 'The specified "childViewContainer" was not found: ' + containerView . childViewContainer } ) ; } } else { container = containerView . $el ; } containerView . $childViewContainer = container ; return container ; }


Input: Ensure the regions are available when the initialize method is called . [CODESPLIT] function ( options ) { options = options || { } ; this . _firstRender = true ; this . _initializeRegions ( options ) ; Marionette . ItemView . call ( this , options ) ; }


Input: LayoutView s render will use the existing region objects the first time it is called . Subsequent calls will destroy the views that the regions are showing and then reset the el for the regions to the newly rendered DOM elements . [CODESPLIT] function ( ) { this . _ensureViewIsIntact ( ) ; if ( this . _firstRender ) { // if this is the first render, don't do anything to // reset the regions this . _firstRender = false ; } else { // If this is not the first render call, then we need to // re-initialize the `el` for each region this . _reInitializeRegions ( ) ; } return Marionette . ItemView . prototype . render . apply ( this , arguments ) ; }


Input: Handle destroying regions and then destroy the view itself . [CODESPLIT] function ( ) { if ( this . isDestroyed ) { return this ; } // #2134: remove parent element before destroying the child views, so // removing the child views doesn't retrigger repaints if ( this . getOption ( 'destroyImmediate' ) === true ) { this . $el . remove ( ) ; } this . regionManager . destroy ( ) ; return Marionette . ItemView . prototype . destroy . apply ( this , arguments ) ; }


Input: internal method to build regions [CODESPLIT] function ( regions ) { var defaults = { regionClass : this . getOption ( 'regionClass' ) , parentEl : _ . partial ( _ . result , this , 'el' ) } ; return this . regionManager . addRegions ( regions , defaults ) ; }


Input: Internal method to initialize the regions that have been defined in a regions attribute on this layoutView . [CODESPLIT] function ( options ) { var regions ; this . _initRegionManager ( ) ; regions = Marionette . _getValue ( this . regions , this , [ options ] ) || { } ; // Enable users to define `regions` as instance options. var regionOptions = this . getOption . call ( options , 'regions' ) ; // enable region options to be a function regionOptions = Marionette . _getValue ( regionOptions , this , [ options ] ) ; _ . extend ( regions , regionOptions ) ; // Normalize region selectors hash to allow // a user to use the @ui. syntax. regions = this . normalizeUIValues ( regions , [ 'selector' , 'el' ] ) ; this . addRegions ( regions ) ; }


Input: Internal method to initialize the region manager and all regions in it [CODESPLIT] function ( ) { this . regionManager = this . getRegionManager ( ) ; this . regionManager . _parent = this ; this . listenTo ( this . regionManager , 'before:add:region' , function ( name ) { this . triggerMethod ( 'before:add:region' , name ) ; } ) ; this . listenTo ( this . regionManager , 'add:region' , function ( name , region ) { this [ name ] = region ; this . triggerMethod ( 'add:region' , name , region ) ; } ) ; this . listenTo ( this . regionManager , 'before:remove:region' , function ( name ) { this . triggerMethod ( 'before:remove:region' , name ) ; } ) ; this . listenTo ( this . regionManager , 'remove:region' , function ( name , region ) { delete this [ name ] ; this . triggerMethod ( 'remove:region' , name , region ) ; } ) ; }


Input: Takes care of getting the behavior class given options and a key . If a user passes in options . behaviorClass default to using that . Otherwise delegate the lookup to the users behaviorsLookup implementation . [CODESPLIT] function ( options , key ) { if ( options . behaviorClass ) { return options . behaviorClass ; } // Get behavior class can be either a flat object or a method return Marionette . _getValue ( Behaviors . behaviorsLookup , this , [ options , key ] ) [ key ] ; }


Input: Iterate over the behaviors object for each behavior instantiate it and get its grouped behaviors . [CODESPLIT] function ( view , behaviors ) { return _ . chain ( behaviors ) . map ( function ( options , key ) { var BehaviorClass = Behaviors . getBehaviorClass ( options , key ) ; var behavior = new BehaviorClass ( options , view ) ; var nestedBehaviors = Behaviors . parseBehaviors ( view , _ . result ( behavior , 'behaviors' ) ) ; return [ behavior ] . concat ( nestedBehaviors ) ; } ) . flatten ( ) . value ( ) ; }


Input: Wrap view internal methods so that they delegate to behaviors . For example onDestroy should trigger destroy on all of the behaviors and then destroy itself . i . e . view . delegateEvents = _ . partial ( methods . delegateEvents view . delegateEvents behaviors ) ; [CODESPLIT] function ( view , behaviors , methodNames ) { _ . each ( methodNames , function ( methodName ) { view [ methodName ] = _ . partial ( methods [ methodName ] , view [ methodName ] , behaviors ) ; } ) ; }


Input: Internal method to build all trigger handlers for a given behavior [CODESPLIT] function ( behavior , i ) { var triggersHash = _ . clone ( _ . result ( behavior , 'triggers' ) ) || { } ; triggersHash = Marionette . normalizeUIKeys ( triggersHash , getBehaviorsUI ( behavior ) ) ; _ . each ( triggersHash , _ . bind ( this . _setHandlerForBehavior , this , behavior , i ) ) ; }


Input: Internal method to create and assign the trigger handler for a given behavior [CODESPLIT] function ( behavior , i , eventName , trigger ) { // Unique identifier for the `this._triggers` hash var triggerKey = trigger . replace ( / ^\S+ / , function ( triggerName ) { return triggerName + '.' + 'behaviortriggers' + i ; } ) ; this . _triggers [ triggerKey ] = this . _view . _buildViewTrigger ( eventName ) ; }


Input: process the route event and trigger the onRoute method call if it exists [CODESPLIT] function ( routeName , routeArgs ) { // make sure an onRoute before trying to call it if ( _ . isFunction ( this . onRoute ) ) { // find the path that matches the current route var routePath = _ . invert ( this . getOption ( 'appRoutes' ) ) [ routeName ] ; this . onRoute ( routeName , routePath , routeArgs ) ; } }


Input: Create a module attached to the application [CODESPLIT] function ( moduleNames , moduleDefinition ) { // Overwrite the module class if the user specifies one var ModuleClass = Marionette . Module . getClass ( moduleDefinition ) ; var args = _ . toArray ( arguments ) ; args . unshift ( this ) ; // see the Marionette.Module object for more information return ModuleClass . create . apply ( ModuleClass , args ) ; }


Input: Internal method to initialize the regions that have been defined in a regions attribute on the application instance [CODESPLIT] function ( options ) { var regions = _ . isFunction ( this . regions ) ? this . regions ( options ) : this . regions || { } ; this . _initRegionManager ( ) ; // Enable users to define `regions` in instance options. var optionRegions = Marionette . getOption ( options , 'regions' ) ; // Enable region options to be a function if ( _ . isFunction ( optionRegions ) ) { optionRegions = optionRegions . call ( this , options ) ; } // Overwrite current regions with those passed in options _ . extend ( regions , optionRegions ) ; this . addRegions ( regions ) ; return this ; }


Input: Internal method to set up the region manager [CODESPLIT] function ( ) { this . _regionManager = this . getRegionManager ( ) ; this . _regionManager . _parent = this ; this . listenTo ( this . _regionManager , 'before:add:region' , function ( ) { Marionette . _triggerMethod ( this , 'before:add:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'add:region' , function ( name , region ) { this [ name ] = region ; Marionette . _triggerMethod ( this , 'add:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'before:remove:region' , function ( ) { Marionette . _triggerMethod ( this , 'before:remove:region' , arguments ) ; } ) ; this . listenTo ( this . _regionManager , 'remove:region' , function ( name ) { delete this [ name ] ; Marionette . _triggerMethod ( this , 'remove:region' , arguments ) ; } ) ; }


Input: Internal method to setup the Wreqr . radio channel [CODESPLIT] function ( ) { this . channelName = _ . result ( this , 'channelName' ) || 'global' ; this . channel = _ . result ( this , 'channel' ) || Backbone . Wreqr . radio . channel ( this . channelName ) ; this . vent = _ . result ( this , 'vent' ) || this . channel . vent ; this . commands = _ . result ( this , 'commands' ) || this . channel . commands ; this . reqres = _ . result ( this , 'reqres' ) || this . channel . reqres ; }


Input: Stop this module by running its finalizers and then stop all of the sub - modules for this module [CODESPLIT] function ( ) { // if we are not initialized, don't bother finalizing if ( ! this . _isInitialized ) { return ; } this . _isInitialized = false ; this . triggerMethod ( 'before:stop' ) ; // stop the sub-modules; depth-first, to make sure the // sub-modules are stopped / finalized before parents _ . invoke ( this . submodules , 'stop' ) ; // run the finalizers this . _finalizerCallbacks . run ( undefined , this ) ; // reset the initializers and finalizers this . _initializerCallbacks . reset ( ) ; this . _finalizerCallbacks . reset ( ) ; this . triggerMethod ( 'stop' ) ; }


Input: Internal method : run the module definition function with the correct arguments [CODESPLIT] function ( definition , customArgs ) { // If there is no definition short circut the method. if ( ! definition ) { return ; } // build the correct list of arguments for the module definition var args = _ . flatten ( [ this , this . app , Backbone , Marionette , Backbone . $ , _ , customArgs ] ) ; definition . apply ( this , args ) ; }


Input: Create a module hanging off the app parameter as the parent object . [CODESPLIT] function ( app , moduleNames , moduleDefinition ) { var module = app ; // get the custom args passed in after the module definition and // get rid of the module name and definition function var customArgs = _ . drop ( arguments , 3 ) ; // Split the module names and get the number of submodules. // i.e. an example module name of `Doge.Wow.Amaze` would // then have the potential for 3 module definitions. moduleNames = moduleNames . split ( '.' ) ; var length = moduleNames . length ; // store the module definition for the last module in the chain var moduleDefinitions = [ ] ; moduleDefinitions [ length - 1 ] = moduleDefinition ; // Loop through all the parts of the module definition _ . each ( moduleNames , function ( moduleName , i ) { var parentModule = module ; module = this . _getModule ( parentModule , moduleName , app , moduleDefinition ) ; this . _addModuleDefinition ( parentModule , module , moduleDefinitions [ i ] , customArgs ) ; } , this ) ; // Return the last module in the definition chain return module ; }


Input: ## Module Classes Module classes can be used as an alternative to the define pattern . The extend function of a Module is identical to the extend functions on other Backbone and Marionette classes . This allows module lifecyle events like onStart and onStop to be called directly . [CODESPLIT] function ( moduleDefinition ) { var ModuleClass = Marionette . Module ; if ( ! moduleDefinition ) { return ModuleClass ; } // If all of the module's functionality is defined inside its class, // then the class can be passed in directly. `MyApp.module("Foo", FooModule)`. if ( moduleDefinition . prototype instanceof ModuleClass ) { return moduleDefinition ; } return moduleDefinition . moduleClass || ModuleClass ; }


Input: Add the module definition and add a startWithParent initializer function . This is complicated because module definitions are heavily overloaded and support an anonymous function module class or options object [CODESPLIT] function ( parentModule , module , def , args ) { var fn = this . _getDefine ( def ) ; var startWithParent = this . _getStartWithParent ( def , module ) ; if ( fn ) { module . addDefinition ( fn , args ) ; } this . _addStartWithParent ( parentModule , module , startWithParent ) ; }


Input: returns function signature name [CODESPLIT] function _sigName ( src ) { if ( ! _ . isFunction ( src ) ) return '' let ret = _ . trim ( _ . replace ( src . toString ( ) , 'function' , '' ) ) ret = ret . substr ( 0 , ret . indexOf ( '(' ) ) return ret || '' }


Input: Requests a { @link Ext . device . filesystem . FileSystem } instance . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem#requestFileSystem: You must specify a `success` callback.' ) ; return null ; } var me = this ; var successCallback = function ( fs ) { var fileSystem = Ext . create ( 'Ext.device.filesystem.FileSystem' , fs ) ; config . success . call ( config . scope || me , fileSystem ) ; } ; window . requestFileSystem ( config . type , config . size , successCallback , config . failure || Ext . emptyFn ) ; }


Input: Returns the name of the entry excluding the path leading to it . [CODESPLIT] function ( ) { var components = this . path . split ( '/' ) ; for ( var i = components . length - 1 ; i >= 0 ; -- i ) { if ( components [ i ] . length > 0 ) { return components [ i ] ; } } return '/' ; }


Input: Moves the entry to a different location on the file system . [CODESPLIT] function ( config ) { if ( config . parent == null ) { Ext . Logger . error ( 'Ext.device.filesystem.Entry#moveTo: You must specify a new `parent` of the entry.' ) ; return null ; } var me = this ; this . getEntry ( { options : config . options || { } , success : function ( sourceEntry ) { config . parent . getEntry ( { options : config . options || { } , success : function ( destinationEntry ) { if ( config . copy ) { sourceEntry . copyTo ( destinationEntry , config . newName , function ( entry ) { config . success . call ( config . scope || me , entry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entry . fullPath , me . fileSystem ) ) ; } , config . failure ) ; } else { sourceEntry . moveTo ( destinationEntry , config . newName , function ( entry ) { config . success . call ( config . scope || me , entry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entry . fullPath , me . fileSystem ) ) ; } , config . failure ) ; } } , failure : config . failure } ) ; } , failure : config . failure } ) ; }


Input: Removes the entry from the file system . [CODESPLIT] function ( config ) { this . getEntry ( { success : function ( entry ) { if ( config . recursively && this . directory ) { entry . removeRecursively ( config . success , config . failure ) } else { entry . remove ( config . success , config . failure ) } } , failure : config . failure } ) }


Input: Looks up the parent directory containing the entry . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem.Entry#getParent: You must specify a `success` callback.' ) ; return null ; } var me = this ; this . getEntry ( { options : config . options || { } , success : function ( entry ) { entry . getParent ( function ( parentEntry ) { config . success . call ( config . scope || me , parentEntry . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , parentEntry . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , parentEntry . fullPath , me . fileSystem ) ) } , config . failure ) } , failure : config . failure } ) }


Input: Requests a Directory from the Local File System [CODESPLIT] function ( config ) { var me = this ; var callback = config . success ; if ( ( config . options && config . options . create ) && this . path ) { var folders = this . path . split ( "/" ) ; if ( folders [ 0 ] == '.' || folders [ 0 ] == '' ) { folders = folders . slice ( 1 ) ; } var recursiveCreation = function ( dirEntry ) { if ( folders . length ) { dirEntry . getDirectory ( folders . shift ( ) , config . options , recursiveCreation , config . failure ) ; } else { callback ( dirEntry ) ; } } ; recursiveCreation ( this . fileSystem . fs . root ) ; } else { this . fileSystem . fs . root . getDirectory ( this . path , config . options , function ( directory ) { config . success . call ( config . scope || me , directory ) ; } , config . failure ) ; } }


Input: Lists all the entries in the directory . [CODESPLIT] function ( config ) { if ( ! config . success ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#readEntries: You must specify a `success` callback.' ) ; return null ; } var me = this ; this . getEntry ( { success : function ( dirEntry ) { var directoryReader = dirEntry . createReader ( ) ; directoryReader . readEntries ( function ( entryInfos ) { var entries = [ ] , i = 0 , len = entryInfos . length ; for ( ; i < len ; i ++ ) { entryInfo = entryInfos [ i ] ; entries [ i ] = entryInfo . isDirectory ? Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , entryInfo . fullPath , me . fileSystem ) : Ext . create ( 'Ext.device.filesystem.FileEntry' , entryInfo . fullPath , me . fileSystem ) ; } config . success . call ( config . scope || this , entries ) ; } , function ( error ) { if ( config . failure ) { config . failure . call ( config . scope || this , error ) ; } } ) ; } , failure : config . failure } ) ; }


Input: Works the same way as { [CODESPLIT] function ( config ) { if ( config . path == null ) { Ext . Logger . error ( 'Ext.device.filesystem.DirectoryEntry#getFile: You must specify a `path` of the file.' ) ; return null ; } var me = this ; var fullPath = this . path + config . path ; var directoryEntry = Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , fullPath , this . fileSystem ) ; directoryEntry . getEntry ( { success : function ( ) { config . success . call ( config . scope || me , directoryEntry ) ; } , options : config . options || { } , failure : config . failure } ) }


Input: Requests a File Handle from the Local File System [CODESPLIT] function ( config ) { var me = this ; var originalConfig = Ext . applyIf ( { } , config ) ; if ( this . fileSystem ) { var failure = function ( evt ) { if ( ( config . options && config . options . create ) && Ext . isString ( this . path ) ) { var folders = this . path . split ( "/" ) ; if ( folders [ 0 ] == '.' || folders [ 0 ] == '' ) { folders = folders . slice ( 1 ) ; } if ( folders . length > 1 && ! config . recursive === true ) { folders . pop ( ) ; var dirEntry = Ext . create ( 'Ext.device.filesystem.DirectoryEntry' , folders . join ( "/" ) , me . fileSystem ) ; dirEntry . getEntry ( { options : config . options , success : function ( ) { originalConfig . recursive = true ; me . getEntry ( originalConfig ) ; } , failure : config . failure } ) ; } else { if ( config . failure ) { config . failure . call ( config . scope || me , evt ) ; } } } else { if ( config . failure ) { config . failure . call ( config . scope || me , evt ) ; } } } ; this . fileSystem . fs . root . getFile ( this . path , config . options || null , function ( fileEntry ) { fileEntry . file ( function ( file ) { me . length = file . size ; originalConfig . success . call ( config . scope || me , fileEntry ) ; } , function ( error ) { failure . call ( config . scope || me , error ) ; } ) ; } , function ( error ) { failure . call ( config . scope || me , error ) ; } ) ; } else { config . failure ( { code : - 1 , message : "FileSystem not Initialized" } ) ; } }


Input: Sets the byte offset into the file at which the next read / write will occur . [CODESPLIT] function ( config ) { if ( config . offset == null ) { Ext . Logger . error ( 'Ext.device.filesystem.FileEntry#seek: You must specify an `offset` in the file.' ) ; return null ; } this . offset = config . offset || 0 ; if ( config . success ) { config . success . call ( config . scope || this ) ; } }


Input: Reads the data from the file starting at the file offset . [CODESPLIT] function ( config ) { var me = this ; this . getEntry ( { success : function ( fileEntry ) { fileEntry . file ( function ( file ) { if ( Ext . isNumber ( config . length ) ) { if ( Ext . isFunction ( file . slice ) ) { file = file . slice ( me . offset , config . length ) ; } else { if ( config . failure ) { config . failure . call ( config . scope || me , { code : - 2 , message : "File missing slice functionality" } ) ; } return ; } } var reader = new FileReader ( ) ; reader . onloadend = function ( evt ) { config . success . call ( config . scope || me , evt . target . result ) ; } ; reader . onerror = function ( error ) { config . failure . call ( config . scope || me , error ) ; } ; if ( config . reader ) { reader = Ext . applyIf ( reader , config . reader ) ; } config . encoding = config . encoding || "UTF8" ; switch ( config . type ) { default : case "text" : reader . readAsText ( file , config . encoding ) ; break ; case "dataURL" : reader . readAsDataURL ( file ) ; break ; case "binaryString" : reader . readAsBinaryString ( file ) ; break ; case "arrayBuffer" : reader . readAsArrayBuffer ( file ) ; break ; } } , function ( error ) { config . failure . call ( config . scope || me , error ) } ) ; } , failure : function ( error ) { config . failure . call ( config . scope || me , error ) } } ) }


Input: Truncates or extends the file to the specified size in bytes . If the file is extended the added bytes are null bytes . [CODESPLIT] function ( config ) { if ( config . size == null ) { Ext . Logger . error ( 'Ext.device.filesystem.FileEntry#write: You must specify a `size` of the file.' ) ; return null ; } var me = this ; //noinspection JSValidateTypes this . getEntry ( { success : function ( fileEntry ) { fileEntry . createWriter ( function ( writer ) { writer . truncate ( config . size ) ; config . success . call ( config . scope || me , me ) ; } , function ( error ) { config . failure . call ( config . scope || me , error ) } ) } , failure : function ( error ) { config . failure . call ( config . scope || me , error ) } } ) }


Input: sorts keys for better readablity [CODESPLIT] function ( obj ) { const keys = _ . sortBy ( _ . keys ( obj ) , function ( key ) { return key ; } ) ; return _ . zipObject ( keys , _ . map ( keys , function ( key ) { return obj [ key ] ; } ) ) ; }


Input: all dependencies done [CODESPLIT] function ( err ) { if ( err ) return done ( err ) ; var ret ; if ( typeof leave == 'function' ) { try { ret = leave . call ( this , child , parent ) ; } catch ( err ) { return done ( err ) ; } } done ( null , ret ) ; }


Input: Multi - Key LRU cache . [CODESPLIT] function MultiKeyCache ( options ) { options = options || { } ; var self = this ; var dispose = options . dispose ; options . dispose = function ( key , value ) { self . _dispose ( key ) ; if ( dispose ) { dispose ( key , value ) ; } } ; this . cache = new LRU ( options ) ; this . _keyMap = { } ; }


Input: NOTE : the this context will be determined at the time the curried function receives its ** final ** argument . [CODESPLIT] function curry ( len , f ) { for ( var _len = arguments . length , initArgs = Array ( _len > 2 ? _len - 2 : 0 ) , _key = 2 ; _key < _len ; _key ++ ) { initArgs [ _key - 2 ] = arguments [ _key ] ; } var _ref = function ( ) { switch ( true ) { case _extractHiddenClass ( len ) === 'Function' : var args = f == null ? [ ] : [ f ] . concat ( initArgs ) ; return [ len , len . length , args ] ; case _extractHiddenClass ( len ) === 'Number' : return [ f , len , initArgs ] ; default : throw new TypeError ( 'Unrecognized arguments ' + len + ' and ' + f + ' to function curry.' ) ; } } ( ) , _ref2 = _slicedToArray ( _ref , 3 ) , fn = _ref2 [ 0 ] , arity = _ref2 [ 1 ] , fnArgs = _ref2 [ 2 ] ; if ( ! fn ) { return function ( fn ) { for ( var _len2 = arguments . length , args = Array ( _len2 > 1 ? _len2 - 1 : 0 ) , _key2 = 1 ; _key2 < _len2 ; _key2 ++ ) { args [ _key2 - 1 ] = arguments [ _key2 ] ; } return curry . apply ( this , [ arity , fn ] . concat ( args ) ) ; } ; } var helper = function helper ( args ) { return function ( ) { for ( var _len3 = arguments . length , rest = Array ( _len3 ) , _key3 = 0 ; _key3 < _len3 ; _key3 ++ ) { rest [ _key3 ] = arguments [ _key3 ] ; } return currier . call ( this , arity , fn , [ ] . concat ( _toConsumableArray ( args ) , rest ) ) ; } ; } ; var currier = function currier ( length , f , args ) { if ( args . length >= length ) { // ES 6 classes and built-ins, real or polyfilled, throw a TypeError if you try to call them // as a function. try { return f . apply ( this , args ) ; } catch ( e ) { if ( e instanceof TypeError ) { return _applyConstructor ( f , args ) ; } else { throw e ; } } } else { return helper ( args ) ; } } ; return currier . call ( this , arity , fn , fnArgs ) ; }


Input: debounce :: Number - > ( * - > Null ) - > Number Delay in milliseconds . Returns the timer ID so caller can cancel [CODESPLIT] function debounce ( n , immed , f ) { var _ref3 = function ( ) { switch ( _extractHiddenClass ( immed ) ) { case 'Boolean' : return [ f , immed ] ; case 'Function' : return [ immed , false ] ; default : throw new TypeError ( 'Unrecognized arguments ' + immed + ' and ' + f + ' to function debounce.' ) ; } } ( ) , _ref4 = _slicedToArray ( _ref3 , 2 ) , fn = _ref4 [ 0 ] , now = _ref4 [ 1 ] ; var timer = null ; return function ( ) { var _this = this ; for ( var _len4 = arguments . length , args = Array ( _len4 ) , _key4 = 0 ; _key4 < _len4 ; _key4 ++ ) { args [ _key4 ] = arguments [ _key4 ] ; } if ( timer === null && now ) { fn . apply ( this , args ) ; } clearTimeout ( timer ) ; timer = setTimeout ( function ( ) { return fn . apply ( _this , args ) ; } , n ) ; return timer ; } ; }


Input: pipe Forward function composition . [CODESPLIT] function pipe ( ) { for ( var _len6 = arguments . length , fs = Array ( _len6 ) , _key6 = 0 ; _key6 < _len6 ; _key6 ++ ) { fs [ _key6 ] = arguments [ _key6 ] ; } return function ( ) { var _this3 = this ; var first = fs . shift ( ) ; for ( var _len7 = arguments . length , args = Array ( _len7 ) , _key7 = 0 ; _key7 < _len7 ; _key7 ++ ) { args [ _key7 ] = arguments [ _key7 ] ; } return fs . reduce ( function ( acc , f ) { return f . call ( _this3 , acc ) ; } , first . apply ( this , args ) ) ; } ; }


Input: denodeify :: ( * - > * ) - > ( * - > Promise * ) Turns a callback - accepting function into one that returns a Promise . [CODESPLIT] function denodeify ( fn ) { var length = fn . length > 0 ? fn . length - 1 : 0 ; var f = function f ( ) { var _this4 = this ; for ( var _len8 = arguments . length , args = Array ( _len8 ) , _key8 = 0 ; _key8 < _len8 ; _key8 ++ ) { args [ _key8 ] = arguments [ _key8 ] ; } return new Promise ( function ( resolve , reject ) { fn . apply ( _this4 , [ ] . concat ( args , [ function ( err ) { for ( var _len9 = arguments . length , rest = Array ( _len9 > 1 ? _len9 - 1 : 0 ) , _key9 = 1 ; _key9 < _len9 ; _key9 ++ ) { rest [ _key9 - 1 ] = arguments [ _key9 ] ; } if ( err ) { reject ( err ) ; } var result = void 0 ; switch ( rest . length ) { case 0 : result = true ; break ; case 1 : result = rest [ 0 ] ; break ; default : result = rest ; break ; } resolve ( result ) ; } ] ) ) ; } ) ; } ; return length ? curry ( length , f ) : f ; }


Input: trampoline :: ( * - > * ) - > ( * - > * ) [CODESPLIT] function trampoline ( fn ) { return curry ( fn . length , function ( ) { for ( var _len10 = arguments . length , args = Array ( _len10 ) , _key10 = 0 ; _key10 < _len10 ; _key10 ++ ) { args [ _key10 ] = arguments [ _key10 ] ; } var result = fn . apply ( this , args ) ; while ( _extractHiddenClass ( result ) === 'Function' ) { result = result ( ) ; } return result ; } ) ; }


Input: Performs a batch of { @link Ext . data . Operation Operations } in the order specified by { @link #batchOrder } . Used internally by { @link Ext . data . Store } s { @link Ext . data . Store#sync sync } method . Example usage : [CODESPLIT] function ( options , /* deprecated */ listeners ) { var me = this , params = options . params , useBatch = me . getBatchActions ( ) , model = me . getModel ( ) , batch , records ; if ( options . operations === undefined ) { // the old-style (operations, listeners) signature was called // so convert to the single options argument syntax options = { operations : options , listeners : listeners } ; // <debug warn> Ext . Logger . deprecate ( 'Passes old-style signature to Proxy.batch (operations, listeners). Please convert to single options argument syntax.' ) ; // </debug> } if ( options . batch && options . batch . isBatch ) { batch = options . batch ; } else { batch = new Ext . data . Batch ( options . batch || { } ) ; } batch . setProxy ( me ) ; batch . on ( 'complete' , Ext . bind ( me . onBatchComplete , me , [ options ] , 0 ) ) ; if ( options . listeners ) { batch . on ( options . listeners ) ; } Ext . each ( me . getBatchOrder ( ) . split ( ',' ) , function ( action ) { records = options . operations [ action ] ; if ( records ) { if ( useBatch ) { var operationOptions = { action : action , records : records , model : model } ; if ( params ) { operationOptions . params = params ; } batch . add ( new Ext . data . Operation ( operationOptions ) ) ; } else { Ext . each ( records , function ( record ) { var operationOptions = { action : action , records : [ record ] , model : model } ; if ( params ) { operationOptions . params = params ; } batch . add ( new Ext . data . Operation ( operationOptions ) ) ; } ) ; } } } , me ) ; batch . start ( ) ; return batch ; }


Input: Creates a raw HTML string for a template . A comment containing the el configuration can be inserted into it . [CODESPLIT] function createRawHtml ( createTemplateFn , templateLanguage , elCommentConfig , dataAttributes ) { // Construct the HTML string var comment = elCommentConfig . noComment ? "" : "<!-- " + elCommentConfig . createContent ( dataAttributes ) + " -->" , insertion = elCommentConfig . among ? comment : "" , isLeading = ! elCommentConfig . trailing && ! elCommentConfig . among , isTrailing = elCommentConfig . trailing , baseTemplate = createTemplateFn ( templateLanguage , insertion ) ; return isLeading ? comment + baseTemplate : isTrailing ? baseTemplate + comment : baseTemplate ; }


Input:
Creates the content of a complex template . It should contain as many pitfalls for correct processing as possible . [CODESPLIT] function createComplexTemplate ( templateLanguage , options ) { var t = getTemplateLanguageConstructs ( templateLanguage ) , indent = options && options . indentation || "" , insert = options && options . insertion || "" , lines = [ '' , '' , t . if , '
This is a %%paragraph' , 'Some random %%text&& with different line breaks.

' , t . else , '
This is a %%header&&
    ' , t . endIf , t . if , '
' , t . endIf , insert , 'Some top-level %%text&&, not wrapped in a tag.

' , '' , "<" + "script>alert( 'foo' );</" + "script>" , '
' , '  some text
' , '<%%tagName&& %%attrs&&>lorem ipsum</%%tagName&&>' , '

Invalid nesting

' , t . partial , '
' , '  ' + t . loop , '
%%dd_name&&
' , '
%%dd_content&&
' , '  ' + t . endLoop , '
' ] , innerContent = _ . map ( lines , function ( line ) { return indent + line ; } ) . join ( "\n" ) ; return innerContent . replace ( / %% / g , t . startDelimiter ) . replace ( / && / g , t . endDelimiter ) ; }


Input: Returns the language constructs for a given template language for use in template creation . [CODESPLIT] function getTemplateLanguageConstructs ( templateLanguage ) { var constructs ; switch ( templateLanguage . toLowerCase ( ) ) { case "handlebars" : constructs = { startDelimiter : "{{" , endDelimiter : "}}" , if : "{{#if isActive}}" , else : "{{else}}" , endIf : "{{/if}}" , loop : "{{#each looped as |value index|}}" , endLoop : "{{/each}}" , partial : '{{> userMessage tagName="h2" }}' } ; break ; case "ejs" : constructs = { startDelimiter : "<%= " , endDelimiter : " %>" , if : "<% if (isActive) { %>" , else : "<% } else { %>" , endIf : "<% } %>" , loop : "<% looped.forEach(function(item) { %>" , endLoop : "<% }); %>" , partial : "<%- include('user/show', {user: user}); %>" } ; break ; case "es6" : constructs = { startDelimiter : "${" , endDelimiter : "}" , if : "" , else : "" , endIf : "" , loop : "" , endLoop : "" , partial : "" } ; break ; default : throw new Error ( 'Unsupported template language "' + templateLanguage + '"' ) ; } return constructs ; }


Input: Define a new model prototype . [CODESPLIT] function defineModel ( modelType , options ) { var primaryAttributes ; var attributes ; var prototype ; var staticProto ; var ModelConstructor ; var typeName ; var namespace ; if ( types . isValidType ( modelType ) . indexes ) { throw ModelException ( 'Model type cannot be an array `{{type}}`' , null , null , { type : String ( modelType ) } ) ; } else if ( models [ modelType ] ) { throw ModelException ( 'Model already defined `{{type}}`' , null , null , { type : String ( modelType ) } ) ; } options = options || { } ; primaryAttributes = [ ] ; namespace = _getNamespace ( modelType ) ; typeName = _getTypeName ( modelType ) ; attributes = _prepareAttributes ( options . attributes || { } , primaryAttributes ) ; prototype = _preparePrototype ( options . methods || { } , primaryAttributes , modelType , namespace , typeName ) ; staticProto = _prepareStaticProto ( options . staticMethods || { } , primaryAttributes , options . attributes , prototype . _type ) ; ModelConstructor = Function ( 'Model, events, attributes' , 'return function ' + typeName + 'Model(data) { ' + 'if (!(this instanceof ' + typeName + 'Model)){' + 'return new ' + typeName + 'Model(data);' + '}' + ( attributes ? 'Object.defineProperties(this, attributes);' : '' ) + 'events.emit("create", data);' + 'Model.call(this, data);' + ' }' ) ( Model , events , attributes ) ; util . inherits ( ModelConstructor , Model ) ; Object . defineProperties ( ModelConstructor . prototype , prototype ) ; Object . defineProperties ( ModelConstructor , staticProto ) ; if ( ! types . isDefined ( modelType ) ) { types . define ( modelType , options . typeValidator || _modelTypeValidator ( ModelConstructor ) ) ; } // assign models [ modelType ] = ModelConstructor ; events . emit ( 'define' , { modelType : modelType , namespace : namespace , typeName : typeName , attributes : attributes , constructor : ModelConstructor , options : options } ) ; // Freeze model API for ( var attr in attributes ) { Object . freeze ( attributes [ attr ] ) ; } if ( options . attributes ) { Object . freeze ( options . attributes ) ; // freeze declared attributes } if ( attributes ) { Object . freeze ( attributes ) ; // freeze attributes list } Object . freeze ( primaryAttributes ) ; // freeze primary attributes //Object.freeze(ModelConstructor.prototype);  // do not freeze to allow extensions return ModelConstructor ; }


Input: Base Model function constructor [CODESPLIT] function Model ( data ) { var attributes = this . __proto__ . constructor . attributes ; var i , ilen ; var dirty = false ; Object . defineProperties ( this , { _id : { configurable : false , enumerable : true , writable : false , value : ++ uniqueId } , _isDirty : { configurable : false , enumerable : true , get : function isDirty ( ) { return dirty ; } , set : function isDirty ( d ) { dirty = d ; if ( ! d && this . _previousData ) { this . _previousData = undefined ; } } } , _isNew : { configurable : false , enumerable : true , get : function isNewModel ( ) { var newModel = false ; var attrValue ; if ( this . _primaryAttributes ) { for ( i = 0 , ilen = this . _primaryAttributes . length ; i < ilen && ! newModel ; ++ i ) { attrValue = this [ this . _primaryAttributes [ i ] ] ; if ( ( attrValue === undefined ) || ( attrValue === null ) ) { newModel = true ; } } } return newModel ; } } } ) ; if ( attributes ) { Object . defineProperties ( this , attributes ) ; Object . defineProperty ( this , '_data' , { configurable : false , enumerable : false , writable : false , value : _defaultData ( attributes ) } ) ; } if ( Array . isArray ( data ) ) { for ( i = 0 , ilen = data . length ; i < ilen ; ++ i ) { if ( this . _primaryAttributes [ i ] ) { this [ this . _primaryAttributes [ i ] ] = data [ i ] ; } } } else if ( data ) { this . fromJSON ( data ) ; } this . _isDirty = false ; // overwrite... }


Input: Create an instance of Point [CODESPLIT] function Point ( masterApikey , feedID , streamID ) { /** @private */ this . masterApiKey = masterApikey ; /** @private */ this . feedID = feedID . toString ( ) ; /** @private */ this . streamID = streamID . toString ( ) ; }


Input: Truncate a string and add an ellipsis ( ... ) to the end if it exceeds the specified length . [CODESPLIT] function ( value , len , word ) { if ( value && value . length > len ) { if ( word ) { var vs = value . substr ( 0 , len - 2 ) , index = Math . max ( vs . lastIndexOf ( ' ' ) , vs . lastIndexOf ( '.' ) , vs . lastIndexOf ( '!' ) , vs . lastIndexOf ( '?' ) ) ; if ( index != - 1 && index >= ( len - 15 ) ) { return vs . substr ( 0 , index ) + "..." ; } } return value . substr ( 0 , len - 3 ) + "..." ; } return value ; }


Input: Pads the left side of a string with a specified character . This is especially useful for normalizing number and date strings . Example usage : [CODESPLIT] function ( val , size , ch ) { var result = String ( val ) ; ch = ch || " " ; while ( result . length < size ) { result = ch + result ; } return result ; }


Input: Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens . Each token must be unique and must increment in the format { 0 } { 1 } etc . Example usage : [CODESPLIT] function ( format ) { var args = Ext . toArray ( arguments , 1 ) ; return format . replace ( Ext . util . Format . formatRe , function ( m , i ) { return args [ i ] ; } ) ; }


Input: Convert certain characters ( & < > and ) to their HTML character equivalents for literal display in web pages . [CODESPLIT] function ( value ) { return ! value ? value : String ( value ) . replace ( / & / g , "&" ) . replace ( / > / g , ">" ) . replace ( / < / g , "<" ) . replace ( / " / g , """ ) ; }


Input:
Parse a value into a formatted date using the specified format pattern . Note that this uses the native Javascript Date . parse () method and is therefore subject to its idiosyncrasies . Most formats assume the local timezone unless specified . One notable exception is YYYY - MM - DD ( note the dashes ) which is typically interpreted in UTC and can cause date shifting . [CODESPLIT] function ( value , format ) { var date = value ; if ( ! value ) { return "" ; } if ( ! Ext . isDate ( value ) ) { date = new Date ( Date . parse ( value ) ) ; if ( isNaN ( date ) ) { // Dates with ISO 8601 format are not well supported by mobile devices, this can work around the issue. if ( this . iso8601TestRe . test ( value ) ) { // Fix for older android browsers to properly implement ISO 8601 formatted dates with timezone if ( Ext . os . is . Android && Ext . os . version . isLessThan ( "3.0" ) ) { /**
                         * This code is modified from the following source: <https://github.com/csnover/js-iso8601>
                         * © 2011 Colin Snover <http://zetafleet.com>
                         * Released under MIT license.
                         */ var potentialUndefinedKeys = [ 1 , 4 , 5 , 6 , 7 , 10 , 11 ] ; var dateParsed , minutesOffset = 0 ; // Capture Groups // 1 YYYY (optional) // 2 MM // 3 DD // 4 HH // 5 mm (optional) // 6 ss (optional) // 7 msec (optional) // 8 Z (optional) // 9 ± (optional) // 10 tzHH (optional) // 11 tzmm (optional) if ( ( dateParsed = / ^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$ / . exec ( value ) ) ) { //Set any undefined values needed for Date to 0 for ( var i = 0 , k ; ( k = potentialUndefinedKeys [ i ] ) ; ++ i ) { dateParsed [ k ] = + dateParsed [ k ] || 0 ; } // Fix undefined month and decrement dateParsed [ 2 ] = ( + dateParsed [ 2 ] || 1 ) - 1 ; //fix undefined days dateParsed [ 3 ] = + dateParsed [ 3 ] || 1 ; // Correct for timezone if ( dateParsed [ 8 ] !== 'Z' && dateParsed [ 9 ] !== undefined ) { minutesOffset = dateParsed [ 10 ] * 60 + dateParsed [ 11 ] ; if ( dateParsed [ 9 ] === '+' ) { minutesOffset = 0 - minutesOffset ; } } // Calculate valid date date = new Date ( Date . UTC ( dateParsed [ 1 ] , dateParsed [ 2 ] , dateParsed [ 3 ] , dateParsed [ 4 ] , dateParsed [ 5 ] + minutesOffset , dateParsed [ 6 ] , dateParsed [ 7 ] ) ) ; } } else { date = value . split ( this . iso8601SplitRe ) ; date = new Date ( date [ 0 ] , date [ 1 ] - 1 , date [ 2 ] , date [ 3 ] , date [ 4 ] , date [ 5 ] ) ; } } } if ( isNaN ( date ) ) { // Dates with the format "2012-01-20" fail, but "2012/01/20" work in some browsers. We'll try and // get around that. date = new Date ( Date . parse ( value . replace ( this . dashesRe , "/" ) ) ) ; //<debug> if ( isNaN ( date ) ) { Ext . Logger . error ( "Cannot parse the passed value " + value + " into a valid date" ) ; } //</debug> } value = date ; } return Ext . Date . format ( value , format || Ext . util . Format . defaultDateFormat ) ; }


Input: Updates this container with the new active item . [CODESPLIT] function ( tabBar , newTab ) { var oldActiveItem = this . getActiveItem ( ) , newActiveItem ; this . setActiveItem ( tabBar . indexOf ( newTab ) ) ; newActiveItem = this . getActiveItem ( ) ; return this . forcedChange || oldActiveItem !== newActiveItem ; }


Input: Creates a new { [CODESPLIT] function ( config ) { if ( config === true ) { config = { } ; } if ( config ) { Ext . applyIf ( config , { ui : this . getUi ( ) , docked : this . getTabBarPosition ( ) } ) ; } return Ext . factory ( config , Ext . tab . Bar , this . getTabBar ( ) ) ; }


Input: Creates new LineSegment out of two points . [CODESPLIT] function ( point1 , point2 ) { var Point = Ext . util . Point ; this . point1 = Point . from ( point1 ) ; this . point2 = Point . from ( point2 ) ; }


Input: Returns the point where two lines intersect . [CODESPLIT] function ( lineSegment ) { var point1 = this . point1 , point2 = this . point2 , point3 = lineSegment . point1 , point4 = lineSegment . point2 , x1 = point1 . x , x2 = point2 . x , x3 = point3 . x , x4 = point4 . x , y1 = point1 . y , y2 = point2 . y , y3 = point3 . y , y4 = point4 . y , d = ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) , xi , yi ; if ( d == 0 ) { return null ; } xi = ( ( x3 - x4 ) * ( x1 * y2 - y1 * x2 ) - ( x1 - x2 ) * ( x3 * y4 - y3 * x4 ) ) / d ; yi = ( ( y3 - y4 ) * ( x1 * y2 - y1 * x2 ) - ( y1 - y2 ) * ( x3 * y4 - y3 * x4 ) ) / d ; if ( xi < Math . min ( x1 , x2 ) || xi > Math . max ( x1 , x2 ) || xi < Math . min ( x3 , x4 ) || xi > Math . max ( x3 , x4 ) || yi < Math . min ( y1 , y2 ) || yi > Math . max ( y1 , y2 ) || yi < Math . min ( y3 , y4 ) || yi > Math . max ( y3 , y4 ) ) { return null ; } return new Ext . util . Point ( xi , yi ) ; }


Input: FUNCTION NAME // FUNCTION : functionName ( fcn ) Returns the name of a function . [CODESPLIT] function functionName ( fcn ) { var name ; if ( ! isFunction ( fcn ) ) { throw new TypeError ( 'invalid input argument. Must provide a function. Value: `' + fcn + '`.' ) ; } if ( isString ( fcn . name ) ) { name = fcn . name ; } else { name = RE . exec ( fcn . toString ( ) ) [ 1 ] ; } return ( name === '' ) ? 'anonymous' : name ; }


Input: / * Class that interprets command line commands using commander . [CODESPLIT] function ( ) { // Defines all the commands with commander. program . version ( env . version ) . description ( 'Tool for generating random numbers from a seed' ) . option ( '-s, --seed <seed>' , 'specify the seed' , Math . random ( ) ) . option ( '-d, --decimal' , 'generates a random decimal number' , false ) . option ( '-r, --range <a>,<b>' , 'generates a random integer in the range inclusive' , this . range ) . parse ( process . argv ) ; // Calls the method that will check the commands // the user has entered. this . switchFunction ( ) ; }


Input: Public stuff Constructor [CODESPLIT] function SteroidsSocket ( options ) { var finalTarget ; if ( options . target && net . isIPv6 ( options . target ) ) { finalTarget = normalize6 ( options . target ) ; } else { finalTarget = options . target ; } this . target = finalTarget ; this . port = options . port || 80 ; this . transport = options . transport || 'TCP' ; this . lport = options . lport || null ; this . timeout = options . timeout || 8000 ; this . allowHalfOpen = options . allowHalfOpen || null ; this . wsProto = options . wsProto || 'sip' ; this . wsPath = options . wsPath || null ; // We init the socket in the send function to be able // to detect timeouts using UDP (no "received" or similar event) }


Input: The libraries don t support any close function so we need this to emulate it . [CODESPLIT] function timeoutCb ( ) { if ( ! received ) { self . emit ( 'error' , { type : 'socket: timeout' , data : 'Connection problem: No response' } ) ; } // Websockets Node module doen't support any close function, we're using the client // https://github.com/Worlize/WebSocket-Node/blob/master/lib/WebSocketClient.js // So we need this var to "emulate" it and avoid returning multiple errors wsError = true ; // We're closing the socket manually, so we need this to avoid errors self . close ( ) ; }


Input: String real width [CODESPLIT] function realWidth ( str ) { if ( str == null ) return 0 ; str = stripANSI ( str ) ; return str . length + ( stripEmoji ( str ) . match ( / [^\x00-\xff] / g ) || [ ] ) . length ; }


Input: Main [CODESPLIT] function PC ( source , config ) { if ( source == null ) return ; this . config = { prefix : '' , suffix : '' , placeholder : ' ' , columnSeparation : ' ' , rowSeparation : "\n" , rowSplitSymbol : "\n" , columnSplitSymbol : "\t" } ; this . _STATS = { originalSource : source , source : null , formatted : null , rows : 0 , columns : 0 , maxWidth : [ ] , width : [ ] , align : [ ] } ; this . params ( config ) ; this . parseSource ( ) ; this . AnalyticAlignment ( ) ; this . format ( ) ; }


Input: Recursivley copy a folder to a given destination if there are conflicts prompt the user . [CODESPLIT] function ( source , destination ) { gulp . src ( source ) . pipe ( conflict ( destination ) ) . pipe ( gulp . dest ( destination ) ) ; }


Input: Recursively copy a template folder to a given destination and apply a template context object for using <% = token % > delimiters and {{ = token }} for filename delimiters ( windows restriction ) . [CODESPLIT] function ( source , destination , context , opts ) { if ( ! opts ) opts = { force : true } ; this . mkdirP ( destination ) ; var files = fs . readdirSync ( source ) ; for ( var i = 0 ; i < files . length ; i ++ ) { var sourceFile = path . join ( source , files [ i ] ) ; var destinationFile = path . join ( destination , files [ i ] ) ; if ( this . isDirectory ( sourceFile ) ) { this . templateDirSync ( sourceFile , destinationFile , context , opts ) ; } else { if ( fs . existsSync ( destinationFile ) && ! opts . force ) { console . log ( 'skipping existing file: ' + files [ i ] ) ; } else { this . templateFileSync ( sourceFile , destinationFile , context ) ; } } } }


Input: Copy a and apply a lodash template to a file based on a given context . The filename can include a {{ = token }} for template delimiters ( windows restriction ) . [CODESPLIT] function ( source , destination , context ) { // To avoid issues with windows use a custom delimiter for file names if ( destination . indexOf ( '{{-' ) !== - 1 ) { _ . templateSettings . escape = / \{\{-(.*?)\}\} / g ; destination = _ . template ( destination , context ) ; } var content = fs . readFileSync ( source , 'utf8' ) . toString ( ) ; var indexContent = _ . template ( content , context ) ; fs . writeFileSync ( destination , indexContent , 'utf8' ) ; }


Input: Shortcut for copying a folder and it s contents recursively to a given destination if the source does not exist it will do nothing . [CODESPLIT] function ( source , destination ) { if ( ! fs . existsSync ( destination ) ) mkdir ( '-p' , destination ) ; cp ( '-R' , source , destination ) ; }


Input: Add assignable properties for tracking . [CODESPLIT] function ( tracker , propList ) { var trackingData = tracker [ trackingKeyName ] ; propList . forEach ( function ( name ) { Object . defineProperty ( tracker , name , { enumerable : true , configurable : true , get : function ( ) { return trackingData . object [ name ] ; } , set : function ( x ) { trackingData . actions . push ( { key : name , set : x , } ) ; trackingData . object [ name ] = x ; } , } ) ; } ) ; }


Input: Add callable methods for tracking . [CODESPLIT] function ( tracker , methodList ) { var trackingData = tracker [ trackingKeyName ] ; methodList . forEach ( function ( name ) { tracker [ name ] = function ( ) { var context = this ; var argsArray = Array . prototype . slice . call ( arguments ) ; // Only record actions called directly on the tracker. if ( this === tracker ) { // Forwarded call should operate on original object. context = trackingData . object ; trackingData . actions . push ( { key : name , arguments : argsArray , } ) ; } return trackingData . object [ name ] . apply ( context , argsArray ) ; } ; } ) ; }


Input: Find all existing properties and methods in the object . [CODESPLIT] function ( object ) { var propList = [ ] ; var methodList = [ ] ; for ( var k in object ) { if ( typeof object [ k ] === "function" ) { methodList . push ( k ) ; } else { propList . push ( k ) ; } } return { propList : propList , methodList : methodList , } ; }


Input: JCM constructor should not be async delay until first operation [CODESPLIT] function ( config , callback , scope ) { // Ext . data . utilities . check ( 'SyncProxy' , 'constructor' , 'config' , config , [ 'store' , 'database_name' , 'key' ] ) ; // Ext . data . SyncProxy . superclass . constructor . call ( this , config ) ; this . store = config . store ; // // System Name // this . store . readValue ( 'Sencha.Sync.system_name' , function ( system_name ) { config . system_name = system_name || Ext . data . UUIDGenerator . generate ( ) ; this . store . writeValue ( 'Sencha.Sync.system_name' , config . system_name , function ( ) { // // Load Configuration // Ext . data . utilities . apply ( this , [ 'readConfig_DatabaseDefinition' , 'readConfig_CSV' , 'readConfig_Generator' ] , [ config ] , function ( ) { if ( this . definition . system_name === undefined ) { this . definition . set ( { system_name : Ext . data . UUIDGenerator . generate ( ) } ) ; } console . log ( "SyncProxy - Opened database '" + config . key + "/" + config . database_name + "/" + config . datastore_name + "'" ) if ( callback ) { callback . call ( scope , this ) } } , this ) ; } , this ) ; } , this ) ; }


Input: Installing a new content . [CODESPLIT] function ( content ) { content = trim ( content ) ; if ( this . mounted ) { invoke ( this , [ Constants . BLOCK , 'setMountedContent' ] , content ) ; } else { dom . contentNode ( this ) . innerHTML = content ; this . upgrade ( ) ; } }


Input: Getting object properties . [CODESPLIT] function ( ) { const props = dom . attrs . toObject ( this ) ; const xprops = this . xprops ; const eprops = get ( xtag , [ 'tags' , this [ Constants . TAGNAME ] , 'accessors' ] , { } ) ; for ( let prop in eprops ) { if ( xprops . hasOwnProperty ( prop ) && eprops . hasOwnProperty ( prop ) && ! BLOCK_COMMON_ACCESSORS . hasOwnProperty ( prop ) ) { props [ prop ] = this [ prop ] ; } } dom . attrs . typeConversion ( props , xprops ) ; return props ; }


Input: Cloning a node . [CODESPLIT] function ( deep ) { // not to clone the contents const node = dom . cloneNode ( this , false ) ; dom . upgrade ( node ) ; node [ Constants . TMPL ] = this [ Constants . TMPL ] ; node [ Constants . INSERTED ] = false ; if ( deep ) { node . content = this . content ; } // ??? // if ('checked' in this) clone.checked = this.checked; return node ; }


Input: Initialization of the element . [CODESPLIT] function blockInit ( node ) { if ( ! node [ Constants . TAGNAME ] ) { node [ Constants . INSERTED ] = false ; node [ Constants . TAGNAME ] = node . tagName . toLowerCase ( ) ; node [ Constants . TMPL ] = { } ; node [ Constants . UID ] = uniqueId ( ) ; return true ; } return false ; }


Input: Creating an item . [CODESPLIT] function blockCreate ( node ) { if ( node . hasChildNodes ( ) ) { Array . prototype . forEach . call ( node . querySelectorAll ( 'script[type="text/x-template"][ref],template[ref]' ) , tmplCompileIterator , node ) ; } node [ Constants . BLOCK ] = new XBElement ( node ) ; }


Input: Special handler of merge . Arrays are merged by the concatenation . [CODESPLIT] function mergeCustomizer ( objValue , srcValue , key ) { if ( isArray ( objValue ) ) { return objValue . concat ( srcValue ) ; } if ( key === 'lifecycle' ) { return mergeWith ( objValue , srcValue , lifecycleCustomizer ) ; } if ( key === 'events' ) { return mergeWith ( objValue , srcValue , eventsCustomizer ) ; } if ( key === 'accessors' ) { return mergeWith ( objValue , srcValue , accessorsCustomizer ) ; } if ( key === 'methods' ) { checkOverriddenMethods ( objValue , srcValue ) ; } }


Input: Inheritance events set property changes . [CODESPLIT] function accessorsCustomizer ( objValue , srcValue ) { const objSetter = get ( objValue , 'set' ) ; const srcSetter = get ( srcValue , 'set' ) ; return merge ( { } , objValue , srcValue , { set : wrap ( objSetter , wrap ( srcSetter , wrapperFunction ) ) } ) ; }