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);
    }

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 ) ; }

Returns an array of every nested view within this view


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)
        };
      }
    }

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 ) } ; } }

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.

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 .


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;
    }

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`.

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 .


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);
        }
      }
    }

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 ) ; } } }

Configured the initial events that the collection view binds to.

Configured the initial events that the collection view binds to .


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);
      }
    }


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();
      }
    }

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.

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 .


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();
        }
      }
    }

Internal method. Separated so that CompositeView can have more control over events being triggered, around the rendering process

Internal method . Separated so that CompositeView can have more control over events being triggered around the rendering process


function() {
      var ChildView;

      var models = this._filteredSortedModels();

      _.each(models, function(child, index) {
        ChildView = this.getChildView(child);
        this.addChild(child, ChildView, index);
      }, this);
    }

function ( ) { var ChildView ; var models = this . _filteredSortedModels ( ) ; _ . each ( models , function ( child , index ) { ChildView = this . getChildView ( child ) ; this . addChild ( child , ChildView , index ) ; } , this ) ; }

Internal method to loop through collection and show each child view.

Internal method to loop through collection and show each child view .


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;
    }

Allow the collection to be sorted by a custom view comparator


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');
      }
    }

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' ) ; } }

Internal method to show an empty view in place of a collection of child views, when the collection is empty

Internal method to show an empty view in place of a collection of child views when the collection is empty


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;
    }

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.

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 .


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);
      }
    }

Internal Method. Add the view to children and render it at the given index.

Internal Method . Add the view to children and render it at the given index .


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;
    }

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 ; }


function(child, ChildViewClass, childViewOptions) {
      var options = _.extend({model: child}, childViewOptions);
      var childView = new ChildViewClass(options);
      Marionette.MonitorDOMRefresh(childView);
      return childView;
    }

function ( child , ChildViewClass , childViewOptions ) { var options = _ . extend ( { model : child } , childViewOptions ) ; var childView = new ChildViewClass ( options ) ; Marionette . MonitorDOMRefresh ( childView ) ; return childView ; }

Build a `childView` for a model in the collection.

Build a childView for a model in the collection .


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;
    }

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.

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 .


function() {
      var elBuffer = document.createDocumentFragment();
      _.each(this._bufferedChildren, function(b) {
        elBuffer.appendChild(b.el);
      });
      return elBuffer;
    }

function ( ) { var elBuffer = document . createDocumentFragment ( ) ; _ . each ( this . _bufferedChildren , function ( b ) { elBuffer . appendChild ( b . el ) ; } ) ; return elBuffer ; }

Create a fragment buffer from the currently buffered children


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);
        }
      }
    }

Append the HTML to the collection's `el`. Override this method to do something other than `.append`.

Append the HTML to the collection s el . Override this method to do something other than . append .


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;
    }

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
;
}

Internal method. Check whether we need to insert the view into the correct position.

Internal method . Check whether we need to insert the view into the correct position .


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);
    }

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 ) ; }

Handle cleanup and other destroying needs for the collection of views


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;
    }

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 ; }

Destroy the child views that this collection view is holding on to, if any

Destroy the child views that this collection view is holding on to if any


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);
        }
      }
    }

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.

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 .


function() {
      var data = {};

      if (this.model) {
        data = _.partial(this.serializeModel, this.model).apply(this, arguments);
      }

      return data;
    }

function ( ) { var data = { } ; if ( this . model ) { data = _ . partial ( this . serializeModel , this . model ) . apply ( this , arguments ) ; } return data ; }

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.

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 .


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;
    }

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 ; }


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');
    }

Render the root template that the children views are appended to


function(options) {
      options = options || {};

      this._firstRender = true;
      this._initializeRegions(options);

      Marionette.ItemView.call(this, options);
    }

function ( options ) { options = options || { } ; this . _firstRender = true ; this . _initializeRegions ( options ) ; Marionette . ItemView . call ( this , options ) ; }

Ensure the regions are available when the `initialize` method is called.

Ensure the regions are available when the initialize method is called .


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);
    }

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.

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 .


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);
    }

Handle destroying regions, and then destroy the view itself.

Handle destroying regions and then destroy the view itself .


function(regions) {
      var defaults = {
        regionClass: this.getOption('regionClass'),
        parentEl: _.partial(_.result, this, 'el')
      };

      return this.regionManager.addRegions(regions, defaults);
    }

function ( regions ) { var defaults = { regionClass : this . getOption ( 'regionClass' ) , parentEl : _ . partial ( _ . result , this , 'el' ) } ; return this . regionManager . addRegions ( regions , defaults ) ; }


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);
    }

Internal method to initialize the regions that have been defined in a `regions` attribute on this layoutView.

Internal method to initialize the regions that have been defined in a regions attribute on this layoutView .


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);
      });
    }

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 ) ; } ) ; }

Internal method to initialize the region manager and all regions in it


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];
      }

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.

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 .


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();
      }

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 ( ) ; }

Iterate over the behaviors object, for each behavior instantiate it and get its grouped behaviors.

Iterate over the behaviors object for each behavior instantiate it and get its grouped behaviors .


function(behavior, i) {
        var triggersHash = _.clone(_.result(behavior, 'triggers')) || {};

        triggersHash = Marionette.normalizeUIKeys(triggersHash, getBehaviorsUI(behavior));

        _.each(triggersHash, _.bind(this._setHandlerForBehavior, this, behavior, i));
      }

function ( behavior , i ) { var triggersHash = _ . clone ( _ . result ( behavior , 'triggers' ) ) || { } ; triggersHash = Marionette . normalizeUIKeys ( triggersHash , getBehaviorsUI ( behavior ) ) ; _ . each ( triggersHash , _ . bind ( this . _setHandlerForBehavior , this , behavior , i ) ) ; }

Internal method to build all trigger handlers for a given behavior


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);
      }

Internal method to create and assign the trigger handler for a given behavior


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);
      }
    }

process the route event and trigger the onRoute method call, if it exists

process the route event and trigger the onRoute method call if it exists


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);
    }

Create a module, attached to the application

Create a module attached to the application


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;
    }

Internal method to initialize the regions that have been defined in a `regions` attribute on the application instance

Internal method to initialize the regions that have been defined in a regions attribute on the application instance


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);
      });
    }

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 ) ; } ) ; }

Internal method to set up the region manager


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;
    }

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 ; }

Internal method to setup the Wreqr.radio channel

Internal method to setup the Wreqr . radio channel


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');
    }

Stop this module by running its finalizers and then stop all of the sub-modules for this module

Stop this module by running its finalizers and then stop all of the sub - modules for this module


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;
    }

Create a module, hanging off the app parameter as the parent object.

Create a module hanging off the app parameter as the parent object .


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);
    }

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 ) ; }

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

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


function _sigName(src) {
  if (!_.isFunction(src)) return ''
  let ret = _.trim(_.replace(src.toString(), 'function', ''))
  ret = ret.substr(0, ret.indexOf('('))
  return ret || ''
}

function _sigName ( src ) { if ( ! _ . isFunction ( src ) ) return '' let ret = _ . trim ( _ . replace ( src . toString ( ) , 'function' , '' ) ) ret = ret . substr ( 0 , ret . indexOf ( '(' ) ) return ret || '' }


function() {
                var components = this.path.split('/');
                for (var i = components.length - 1; i >= 0; --i) {
                    if (components[i].length > 0) {
                        return components[i];
                    }
                }

                return '/';
            }

function ( ) { var components = this . path . split ( '/' ) ; for ( var i = components . length - 1 ; i >= 0 ; -- i ) { if ( components [ i ] . length > 0 ) { return components [ i ] ; } } return '/' ; }

Returns the name of the entry, excluding the path leading to it.

@return {String}
The entry name.

Returns the name of the entry excluding the path leading to it .


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
                    }
                );
            }

Moves the entry to a different location on the file system.

@param {Object} config
The object which contains the following config options:

@param {Ext.device.filesystem.DirectoryEntry} config.parent This is required.
The directory to which to move the entry.

@param {String} config.newName This is optional.
The new name of the entry to move. Defaults to the entry's current name if unspecified.

@param {Function} config.success This is optional.
The callback to be called when the entry has been successfully moved.

@param {Ext.device.filesystem.Entry} config.success.entry
The entry for the new location.

@param {Function} config.failure This is optional.
The callback to be called when an error occurred.

@param {Object} config.failure.error
The occurred error.

@param {Object} config.scope
The scope object

Moves the entry to a different location on the file system .


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
                    }
                )
            }

Looks up the parent directory containing the entry.

@param {Object} config
The object which contains the following config options:

@param {Function} config.success This is required.
The callback to be called when the parent directory has been successfully selected.

@param {Ext.device.filesystem.DirectoryEntry} config.success.entry
The parent directory of the entry.

@param {Function} config.failure This is optional.
The callback to be called when an error occurred.

@param {Object} config.failure.error
The occurred error.

@param {Object} config.scope
The scope object

Looks up the parent directory containing the entry .


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
                    );
                }
            }

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 ) ; } }

Requests a Directory from the Local File System

@param {Object} config

@param {Object} config.options
File creation options {create:true, exclusive:false}

@param {Boolean} config.options.create
Indicates if the directory should be created if it doesn't exist

@param {Boolean} config.options.exclusive
Used with the create option only indicates whether a creation causes an error if the directory already exists

@param {Function} config.success
The function called when the Directory is returned successfully

@param {Ext.device.filesystem.DirectoryEntry} config.success.directory
DirectoryEntry Object

@param {Function} config.failure
The function called when the Directory request causes an error

@param {FileError} config.failure.error


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"});
                }
            }

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
||
,
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"
}
)
;
}
}

Requests a File Handle from the Local File System

@param {Object} config

@param {String} config.file
Filename optionally including path in string format '/tmp/debug.txt' or a File Object

@param {Object} config.options
File creation options {create:true, exclusive:false}

@param {Boolean} config.options.create
Indicates if the file should be created if it doesn't exist

@param {Boolean} config.options.exclusive
Used with the create option only indicates whether a creation causes an error if the file already exists

@param {Function} config.success
The function called when the filesystem is returned successfully

@param {FileSystem} config.success.entry

@param {Function} config.failure
The function called when the filesystem request causes and error

@param {FileError} config.failure.error


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)
                        }
                    }
                )
            }

Truncates or extends the file to the specified size in bytes.
If the file is extended, the added bytes are null bytes.

@param {Object} config
The object which contains the following config options:

@param {Number} config.size This is required.
The new file size.

@param {Function} config.success This is optional.
The callback to be called when the file size has been successfully changed.

@param {Function} config.failure This is optional.
The callback to be called when an error occurred.

@param {Object} config.failure.error
The occurred error.

@param {Object} config.scope
The scope object

Truncates or extends the file to the specified size in bytes . If the file is extended the added bytes are null bytes .


function (obj) {
    const keys = _.sortBy(_.keys(obj), function (key) {
      return key;
    });
    return _.zipObject(keys, _.map(keys, function (key) {
      return obj[key];
    }));
  }

function ( obj ) { const keys = _ . sortBy ( _ . keys ( obj ) , function ( key ) { return key ; } ) ; return _ . zipObject ( keys , _ . map ( keys , function ( key ) { return obj [ key ] ; } ) ) ; }


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);
    }

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 ) ; }


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 = {};
}

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 = { } ; }

Multi-Key LRU cache.
@class
@param {object} options Options for the cache.


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));
    };
  }

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 ) ) ; } ; }


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;
}

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
;
}

Creates a raw HTML string for a template. A comment containing the el configuration can be inserted into it.

By default, the comment is inserted at the beginning of the HTML string.

@param   {Function} createTemplateFn  the function returning the template HTML, except for the el comment. It  must
be possible to pass the el comment as an insertion. Expected signature:
createTemplateFn( templateLanguage, insertion )
@param   {string} templateLanguage    currently supported: "Handlebars", "EJS" (EJS), "ES6". It is up to the template
creation function what to make of it (e.g., can be ignored if there are no
template vars)
@param   {Object} elCommentConfig
@param   {Function} [elCommentConfig.createContent]    a function generating the content of the comment which defines
the el, except for the outer comment tags (not wrapped in
"<!-- ... -->"). Called with the data attributes (as a hash).
Expected signature: createContent( dataAttributes )
@param   {boolean}  [elCommentConfig.noComment=false]  flag: comment should be omitted
@param   {boolean}  [elCommentConfig.trailing=false]   flag: comment should be placed at the end of the HTML
@param   {boolean}  [elCommentConfig.among=false]      flag: comment should be placed inside the HTML
@param   {Object}   [dataAttributes]                   hash containing the data attributes to be set in the comment

@returns {string}

Creates a raw HTML string for a template . A comment containing the el configuration can be inserted into it .


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 );
}

'<!-- top-level comment (single line) -->'

'<!-- comment containing a <div> tag -->'

Creates the content of a complex template. It should contain as many pitfalls for correct processing as possible.

Features:

- has a top-level comment (single line)
- has a top-level comment (multi-line)
- has a comment containing a tag
- has numerous top-level tags
- has text at top level, not enclosed in another tag
- has tags nested in invalid ways, creating invalid HTML (<h1> inside <p>)
- has significant whitespace which must be preserved
- has template vars inside a tag itself (defining attributes)
- has a template var define the tag type
- has templating instructions (if/else)
- has a script tag inside the template, containing Javascript
- has a reference to a partial template

NB For ES6 templates, only the start and end delimiters used for a variable are supported, other constructs (if, loop,
partial) are omitted here.

@param   {string} templateLanguage          values are "Handlebars", "EJS" (EJS), "ES6"
@param   {object} [options]
@param   {string} [options.indentation=""]  a string of whitespace, e.g. "   " or "" (no indentation)
@param   {string} [options.insertion=""]    an additional string which is inserted somewhere in the middle of the
content (if left undefined, a blank line, plus insertion, appears instead)
@returns {string}

Creates the content of a complex template . It should contain as many pitfalls for correct processing as possible .


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;
}

Returns the language constructs for a given template language, for use in template creation.

NB For ES6 templates, only the start and end delimiters used for a variable are supported, other constructs (if, loop,
partial) are omitted here. Empty strings are returned for the instead.

@param   {string} templateLanguage
@returns {Object}

Returns the language constructs for a given template language for use in template creation .


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;
}

Define a new model prototype.

This will define a new model

@param {String} modelType         the model type name
@param {Object} options           the model options
@return {Function}                the model constructor


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...
}

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
===
)
)
{
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...
}

Base Model function constructor

@param {Object} data      the model data


function Point(masterApikey, feedID, streamID) {
  /** @private */this.masterApiKey  = masterApikey;
  /** @private */this.feedID   = feedID.toString();
  /** @private */this.streamID = streamID.toString();
}

function
Point
(
masterApikey
,
feedID
,
streamID
)
{
/** @private */
this
.
masterApiKey
=
masterApikey
;
/** @private */
this
.
feedID
=
feedID
.
toString
(
)
;
/** @private */
this
.
streamID
=
streamID
.
toString
(
)
;
}

Create an instance of Point

@constructor {Point}
@this        {Point}
@param       {string}     masterApikey Your pachube api key.


function(tabBar, newTab) {
        var oldActiveItem = this.getActiveItem(),
            newActiveItem;

        this.setActiveItem(tabBar.indexOf(newTab));
        newActiveItem = this.getActiveItem();
        return this.forcedChange || oldActiveItem !== newActiveItem;
    }

function ( tabBar , newTab ) { var oldActiveItem = this . getActiveItem ( ) , newActiveItem ; this . setActiveItem ( tabBar . indexOf ( newTab ) ) ; newActiveItem = this . getActiveItem ( ) ; return this . forcedChange || oldActiveItem !== newActiveItem ; }

Updates this container with the new active item.
@param {Object} tabBar
@param {Object} newTab
@return {Boolean}

Updates this container with the new active item .


function(point1, point2) {
        var Point = Ext.util.Point;

        this.point1 = Point.from(point1);
        this.point2 = Point.from(point2);
    }

function ( point1 , point2 ) { var Point = Ext . util . Point ; this . point1 = Point . from ( point1 ) ; this . point2 = Point . from ( point2 ) ; }

Creates new LineSegment out of two points.
@param {Ext.util.Point} point1
@param {Ext.util.Point} point2

Creates new LineSegment out of two points .


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);
    }

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 ) ; }

Returns the point where two lines intersect.
@param {Ext.util.LineSegment} lineSegment The line to intersect with.
@return {Ext.util.Point}

Returns the point where two lines intersect .


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)
}


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();
    }

The libraries don't support any close function, so we need this to emulate it.

The libraries don t support any close function so we need this to emulate it .


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

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

String real width

@param {string} str
@returns {number}

Emoji: 2
Double-byte character: 2
Others: 1


function (source, destination)
    {
      gulp.src(source)
        .pipe(conflict(destination))
        .pipe(gulp.dest(destination));
    }

function ( source , destination ) { gulp . src ( source ) . pipe ( conflict ( destination ) ) . pipe ( gulp . dest ( destination ) ) ; }

Recursivley copy a folder to a given destination, if there are conflicts prompt the user.
@param source
@param destination

Recursivley copy a folder to a given destination if there are conflicts prompt the user .


function (source, destination)
    {
      if (!fs.existsSync(destination))
        mkdir('-p', destination);

      cp('-R', source, destination);
    }

function ( source , destination ) { if ( ! fs . existsSync ( destination ) ) mkdir ( '-p' , destination ) ; cp ( '-R' , source , destination ) ; }

Shortcut for copying a folder and it's contents recursively to a given destination,
if the source does not exist, it will do nothing.
@param source
@param destination

Shortcut for copying a folder and it s contents recursively to a given destination if the source does not exist it will do nothing .


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;
      },
    });
  });
}

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 ; } , } ) ; } ) ; }

Add assignable properties for tracking .


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);
    };
  });
}


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,
  };
}

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 , } ; }

Find all existing properties and methods in the object.

Find all existing properties and methods in the object .


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);
  }

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
)
;
}

JCM constructor should not be async, delay until first operation

JCM constructor should not be async delay until first operation


function (content) {
            content = trim(content);

            if (this.mounted) {
                invoke(this, [ Constants.BLOCK, 'setMountedContent' ], content);

            } else {
                dom.contentNode(this).innerHTML = content;
                this.upgrade();
            }
        }

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

Installing a new content.
@param {string} content


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;
        }

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 ; }

Getting object properties.
@returns {Object}
@readonly


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;
    }

Cloning a node.
@param {boolean} deep true if the content to be saved
@returns {HTMLElement}


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;
}

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 ; }

Initialization of the element.
@example
blockInit(node);
@param {HTMLElement} node
@returns {boolean}
@private


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);
}

Creating an item.
@example
blockCreate(node);
@param {HTMLElement} node
@private


function accessorsCustomizer(objValue, srcValue) {
    const objSetter = get(objValue, 'set');
    const srcSetter = get(srcValue, 'set');

    return merge({}, objValue, srcValue, {
        set: wrap(objSetter, wrap(srcSetter, wrapperFunction))
    });
}

function accessorsCustomizer ( objValue , srcValue ) { const objSetter = get ( objValue , 'set' ) ; const srcSetter = get ( srcValue , 'set' ) ; return merge ( { } , objValue , srcValue , { set : wrap ( objSetter , wrap ( srcSetter , wrapperFunction ) ) } ) ; }

Inheritance events "set" property changes.
@example
_.mergeWith(objValue, srcValue, accessorsCustomizer);
@param {Object} [objValue] the current value
@param {Object} [srcValue] the new value
@returns {Object}
@private

Inheritance events set property changes .


function wrapperEvents(srcFunc, objFunc, ...args) {
    const event = (args[ 0 ] instanceof Event) && args[ 0 ];
    const isStopped = event ? () => event.immediatePropagationStopped : stubFalse;

    if (!isStopped() && isFunction(objFunc)) {
        objFunc.apply(this, args);
    }

    if (!isStopped() && isFunction(srcFunc)) {
        srcFunc.apply(this, args);
    }
}

function wrapperEvents ( srcFunc , objFunc , ... args ) { const event = ( args [ 0 ] instanceof Event ) && args [ 0 ] ; const isStopped = event ? ( ) => event . immediatePropagationStopped : stubFalse ; if ( ! isStopped ( ) && isFunction ( objFunc ) ) { objFunc . apply ( this , args ) ; } if ( ! isStopped ( ) && isFunction ( srcFunc ) ) { srcFunc . apply ( this , args ) ; } }

Implementation of inherited event.
@example
// call objFunc, srcFunc
_.wrap(objFunc, _.wrap(srcFunc, wrapperEvents));
@param {function} [srcFunc]
@param {function} [objFunc]
@param {...*} args
@private


function accessorsIterator(options, name, accessors) {
    const optionsSetter = get(options, 'set');
    const updateSetter = wrap(name, wrapperAccessorsSetUpdate);

    accessors[ name ] = merge({}, options, {
        set: wrap(optionsSetter, wrap(updateSetter, wrapperFunction))
    });
}

function accessorsIterator ( options , name , accessors ) { const optionsSetter = get ( options , 'set' ) ; const updateSetter = wrap ( name , wrapperAccessorsSetUpdate ) ; accessors [ name ] = merge ( { } , options , { set : wrap ( optionsSetter , wrap ( updateSetter , wrapperFunction ) ) } ) ; }

The assignment of parameters accessors.
@example
_.forEach({}, accessorsIterator);
@param {Object} options
@param {string} name
@param {Object} accessors
@private

The assignment of parameters accessors .


function wrapperAccessorsSetUpdate(accessorName, nextValue, prevValue) {
    if (nextValue !== prevValue && this.xprops.hasOwnProperty(accessorName) && this.mounted) {
        this[ Constants.BLOCK ].update();
    }
}

function wrapperAccessorsSetUpdate ( accessorName , nextValue , prevValue ) { if ( nextValue !== prevValue && this . xprops . hasOwnProperty ( accessorName ) && this . mounted ) { this [ Constants . BLOCK ] . update ( ) ; } }

Update element when a property is changed.
@example
// call node.xblock.update();
_.wrap("accessor-name", wrapperAccessorsSetUpdate).call(node, 'newValue', 'oldValue');
@param {string} accessorName the name of the property
@param {*} nextValue
@param {*} prevValue
@this HTMLElement
@private

Update element when a property is changed .


function lifecycleRemoved() {
    this[ Constants.INSERTED ] = false;

    const block = this[ Constants.BLOCK ];

    if (block) {
        block.destroy();
        this[ Constants.BLOCK ] = undefined;
    }
}

function lifecycleRemoved ( ) { this [ Constants . INSERTED ] = false ; const block = this [ Constants . BLOCK ] ; if ( block ) { block . destroy ( ) ; this [ Constants . BLOCK ] = undefined ; } }

The callback of the remote in DOM.
@this HTMLElement
@private


function lifecycleInserted() {
    if (this[ Constants.INSERTED ]) {
        return;
    }

    blockInit(this);

    this[ Constants.INSERTED ] = true;

    const isScriptContent = Boolean(this.querySelector('script'));

    // asynchronous read content
    // <xb-test>
not found
</xb-test>
    if (isScriptContent) {
        lazy(blockCreateLazy, this);

    } else {
        blockCreate(this);
    }
}

The callback of the insert in DOM.
@this HTMLElement
@private


function (obj, removeProp) {
        var newObj = {};
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop) || prop === removeProp) {
                continue;
            }
            newObj[prop] = obj[prop];
        }

        return newObj;
    }

function ( obj , removeProp ) { var newObj = { } ; for ( var prop in obj ) { if ( ! obj . hasOwnProperty ( prop ) || prop === removeProp ) { continue ; } newObj [ prop ] = obj [ prop ] ; } return newObj ; }

Returns copy of `obj` without `removeProp` field.
@param obj
@param removeProp
@returns Object

Returns copy of obj without removeProp field .


function toDashedProperties ( hash ) {
    var transformed = {};

    _.each( hash, function ( value, key ) {
        transformed[toDashed( key )] = value;
    } );

    return transformed;
}

function toDashedProperties ( hash ) { var transformed = { } ; _ . each ( hash , function ( value , key ) { transformed [ toDashed ( key ) ] = value ; } ) ; return transformed ; }

Returns a transformed hash in which all camelCased property names have been replaced by dashed property names. The
input hash remains untouched.

Property values are not modified.

Simple implementation, but good enough for the attribute names we deal with here.

Example: { fooBar: "whatEver" } => { "foo-bar": "whatEver" }

@param   {Object} hash
@returns {Object}

Returns a transformed hash in which all camelCased property names have been replaced by dashed property names . The input hash remains untouched .


function toCamelCasedProperties ( hash ) {
    var transformed = {};

    _.each( hash, function ( value, key ) {
        transformed[toCamelCase( key )] = value;
    } );

    return transformed;
}

function toCamelCasedProperties ( hash ) { var transformed = { } ; _ . each ( hash , function ( value , key ) { transformed [ toCamelCase ( key ) ] = value ; } ) ; return transformed ; }

Returns a transformed hash in which all dashed property names have been replaced by camelCased property names. The
input hash remains untouched.

Property values are not modified.

Simple implementation, but good enough for the attribute names we deal with here.

Example: { "foo-bar": "what-ever" } => { fooBar: "what-ever" }

@param   {Object} hash
@returns {Object}

Returns a transformed hash in which all dashed property names have been replaced by camelCased property names . The input hash remains untouched .


function dashedKeyAlternatives ( hash ) {
    var keys = _.keys( toDashedProperties( hash ) );
    return _.filter( keys, function ( key ) {
            return key.search(/[^-]-[a-z]/) !== -1;
        } );
}

function dashedKeyAlternatives ( hash ) { var keys = _ . keys ( toDashedProperties ( hash ) ) ; return _ . filter ( keys , function ( key ) { return key . search ( / [^-]-[a-z] / ) !== - 1 ; } ) ; }

Returns an array of dashed key names, which are the alternative names for all camel-cased key names in a hash.

Simple key names (not camel-cased) are ignored and don't show up in the array.

E.g., dashedKeyAlternatives( { foo: "whatever", barBaz: "whatever" } ) returns [ "bar-baz" ].

@param   {Object} hash
@returns {string[]}

Returns an array of dashed key names which are the alternative names for all camel - cased key names in a hash .


function(selector, root) {
            var selectors = selector.split(','),
                length = selectors.length,
                i = 0,
                results = [],
                noDupResults = [],
                dupMatcher = {},
                query, resultsLn, cmp;

            for (; i < length; i++) {
                selector = Ext.String.trim(selectors[i]);
                query = this.parse(selector);
//                query = this.cache[selector];
//                if (!query) {
//                    this.cache[selector] = query = this.parse(selector);
//                }
                results = results.concat(query.execute(root));
            }

            // multiple selectors, potential to find duplicates
            // lets filter them out.
            if (length > 1) {
                resultsLn = results.length;
                for (i = 0; i < resultsLn; i++) {
                    cmp = results[i];
                    if (!dupMatcher[cmp.id]) {
                        noDupResults.push(cmp);
                        dupMatcher[cmp.id] = true;
                    }
                }
                results = noDupResults;
            }
            return results;
        }

//                query = this.cache[selector];

Returns an array of matched Components from within the passed root object.

This method filters returned Components in a similar way to how CSS selector based DOM
queries work using a textual selector string.

See class summary for details.

@param {String} selector The selector string to filter returned Components
@param {Ext.Container} root The Container within which to perform the query.
If omitted, all Components within the document are included in the search.

This parameter may also be an array of Components to filter according to the selector.
@return {Ext.Component[]} The matched Components.

@member Ext.ComponentQuery

Returns an array of matched Components from within the passed root object .


function(component, selector) {
            if (!selector) {
                return true;
            }
            var query = this.cache[selector];
            if (!query) {
                this.cache[selector] = query = this.parse(selector);
            }
            return query.is(component);
        }

function ( component , selector ) { if ( ! selector ) { return true ; } var query = this . cache [ selector ] ; if ( ! query ) { this . cache [ selector ] = query = this . parse ( selector ) ; } return query . is ( component ) ; }

Tests whether the passed Component matches the selector string.
@param {Ext.Component} component The Component to test.
@param {String} selector The selector string to test against.
@return {Boolean} `true` if the Component matches the selector.
@member Ext.ComponentQuery

Tests whether the passed Component matches the selector string .


function RouterDecorator (Router) {

  function TelemetryRouter (options) {
    if (!(this instanceof TelemetryRouter)) {
      return new TelemetryRouter(options)
    }

    Router.call(this, options)
  }

  inherits(TelemetryRouter, Router)

  /**
   * Wraps getNearestContacts with telemetry
   * #getNearestContacts
   * @returns {Array} shortlist
   */
  TelemetryRouter.prototype.getNearestContacts = function (key, limit, id, cb) {
    var self = this
    var callback = function (err, shortlist) {
      if (!err) {
        self._log.debug('sorting shortlist based on telemetry score')
        var profiles = {}
        each(shortlist, function (contact, iteratorCallback) {
          var profileCallback = function (err, profile) {
            profiles[contact.nodeID] = profile
            iteratorCallback(err)
          }
          self._rpc.telemetry.getProfile(contact, profileCallback)
        }, function (err) {
          if (err) {
            cb(null, shortlist)
          } else {
            shortlist.sort(self._compare.bind(self, profiles))
            cb(null, shortlist)
          }
        })
      } else {
        cb(err, null)
      }
    }
    Router.prototype.getNearestContacts.call(this, key, limit, id, callback)
  }

  /**
   * Uses the transport telemetry to compare two nodes
   * #_compare
   * @param {kad.Contact} contactA
   * @param {kad.Contact} contactB
   * @returns {Number}
   */
  TelemetryRouter.prototype._compare = function (profiles, cA, cB) {
    var profileA = profiles[cA.nodeID]
    var profileB = profiles[cB.nodeID]
    var scoresA = {}
    var scoresB = {}

    this._rpc._telopts.metrics.forEach(function (Metric) {
      var m = new Metric()
      scoresA[m.key] = Metric.score(m.getMetric(profileA))
      scoresB[m.key] = Metric.score(m.getMetric(profileB))
    })

    var resultA = TelemetryRouter.getSuccessProbability(scoresA)
    var resultB = TelemetryRouter.getSuccessProbability(scoresB)

    this._log.debug(
      'success probability is %d% vs %d%',
      (resultA * 100).toFixed(3),
      (resultB * 100).toFixed(3)
    )

    // results are close to each other, break tie with throughput score
    if (Math.abs(resultB - resultA) <= 0.005) {
      this._log.debug(
        'score difference is within threshold, selecting based on throughput'
      )
      return scoresB.throughput - scoresA.throughput
    }

    return resultB - resultA
  }

  /**
   * Uses a profile scorecard to calculate the probability of success
   * #getSuccessProbability
   * @param {Object} score
   * @returns {Number}
   */
  TelemetryRouter.getSuccessProbability = function (score) {
    return (score.reliability + score.availability + score.latency) / 3
  }

  return TelemetryRouter
}

Returns a decorated router that wraps node selection
@constructor
@param {kad.Router} Router


function(config) {
                if (!this.active) {
                    Ext.Logger.error('Ext.device.sqlite.SQLTransaction#executeSql: An attempt was made to use a SQLTransaction that is no longer usable.');
                    return null;
                }

                if (config.sqlStatement == null) {
                    Ext.Logger.error('Ext.device.sqlite.SQLTransaction#executeSql: You must specify a `sqlStatement` for the transaction.');
                    return null;
                }

                this.statements.push({
                    sqlStatement: config.sqlStatement,
                    arguments: config.arguments,
                    callback: config.callback,
                    failure: config.failure,
                    scope: config.scope
                });
            }

Executes an SQL statement.

@param {Object} config
The object which contains the following config options:

@param {String} config.sqlStatement This is required.
The SQL statement to execute.

@param {Array} config.arguments This is optional.
The arguments array to bind each '?' placeholder in the SQL statement.

@param {Function} config.callback This is optional.
The callback to be called when the SQL statement succeeded.

@param {Ext.device.sqlite.SQLTransaction} config.callback.transaction
The transaction of the SQL statement.

@param {Ext.device.sqlite.SQLTransaction} config.callback.resultSet
The result of the SQL statement.

@param {Function} config.failure This is optional.
The callback to be called when an error occurred.
If the callback returns false, next SQL statement will be executed.

@param {Ext.device.sqlite.SQLTransaction} config.failure.transaction
The transaction of the SQL statement.

@param {Object} config.failure.error
The occurred error.

@param {Object} config.scope
The scope object


function(index) {
                        if (index < this.getLength()) {
                            var item = {};
                            var row = this.rows[index];
                            this.names.forEach(function(name, index) {
                                item[name] = row[index];
                            });

                            return item;
                        }

                        return null;
                    }

function ( index ) { if ( index < this . getLength ( ) ) { var item = { } ; var row = this . rows [ index ] ; this . names . forEach ( function ( name , index ) { item [ name ] = row [ index ] ; } ) ; return item ; } return null ; }

Returns a row at specified index returned by the SQL statement.
If there is no such row, returns null.

@param {Number} index This is required.
The index of a row.

@return {Object}
The row.

Returns a row at specified index returned by the SQL statement . If there is no such row returns null .


function createPayload(name, level, data) {
  return {
    date: getDate(),
    level: level,
    name: name,
    data: data
  };
}

function createPayload ( name , level , data ) { return { date : getDate ( ) , level : level , name : name , data : data } ; }

Function that create a JSON structure to be logged

@param {string} name - Name of the logger
@param {int} level - Logging level. E.g. log, warn, error
@param {object} data - application data to be logged

@returns {{date: Date, level: int, name: string, data: object}}
Meta data to be logged