Exemple #1
0
 show: function(newView, oldView) {
     document.title = _.result(newView, 'pageTitle') || pageTitle;
     document.scrollTop = 0;
     //when a page gets switched make it visible in the top-menu
     dom.addClass(newView.el, 'active');
     app.currentPage = newView;
 }
  mergeInNestedCollectionErrors(errObj = {}) {
    const nested = _.result(this, 'nested', []);
    let mergedErrs = errObj;

    Object.keys(nested || {})
      .forEach((key) => {
        if (this.get(key) instanceof Collection) {
          const nestedCl = this.get(key);

          nestedCl.forEach((nestedMd) => {
            const prefixedErrs = {};
            const nestedMdErrs = nestedMd.isValid() ? {} : nestedMd.validationError;

            Object.keys(nestedMdErrs).forEach((nestedMdErrKey) => {
              // since indexes can change, we'll index using the model's client id (cid)
              const prefixedKey = `${key}[${nestedMd.cid}].${nestedMdErrKey}`;
              prefixedErrs[prefixedKey] = errObj[prefixedKey] || [];
              prefixedErrs[prefixedKey].push(nestedMdErrs[nestedMdErrKey]);
            });

            mergedErrs = {
              ...mergedErrs,
              ...prefixedErrs,
            };
          });
        }
      });

    return mergedErrs;
  }
    _bind_routes: function(options) {
        if (!this.routes) {
            throw Error("No routes specified for this router ");
        }

        if (!this.app) {
            throw Error("No express application specified to bind this router");
        }

        //internal express router for this router 
        this._express_router = express.Router({
            caseSensitive: options.caseSensitive || false,
            strict: options.strict || false,
            mergeParams: options.mergeParams || false
        });


        this.routes = _.result(this, 'routes');

        var self = this;

        Object.keys(this.routes).forEach(function eachRoute(route) {

            var method = route.split('|')[1] || 'get';
            var url = route.split('|')[0];

            self._express_router[method]('/' + url, function(request, response, next) {
                self._get_handler(route)(request, response, next);
            });
        });
    },
            .on('shown.bs.dropdown', '.dropdown, .dropup', function(e) {
                if (e.namespace !== 'bs.dropdown') {
                    // handle only events triggered with proper NS (omit just any shown events)
                    return;
                }
                var $dropdown = $(this);
                var $dropdownMenu = $('>.dropdown-menu', $dropdown);
                var options = $dropdownMenu.data('options');
                if ($dropdownMenu.length === 0 || ($dropdown.closest('.ui-dialog').length === 0 &&
                    !_.result(options, 'flipMode'))) {
                    // handles only case when dropdown id opened in dialog
                    return;
                }

                $dropdown.data('original-dropstate', $dropdown.hasClass('dropup') ? 'dropup' : 'dropdown');

                var dialogEvents = _.map(['dialogresize', 'dialogdrag', 'dialogreposition'], function(item) {
                    return item + '.autoflip-dropdown';
                });
                var handlePositionChange = _.partial(updatePosition, $dropdown);

                $dropdown.on('shown.autoflip-dropdown', null, {preferCurrentState: true}, handlePositionChange);
                $dropdown.closest('.ui-dialog').on(dialogEvents.join(' '), handlePositionChange);
                $dropdown.parents().on('scroll.autoflip-dropdown', handlePositionChange);
                $dropdown.on('content:changed.autoflip-dropdown', handlePositionChange);
                $(window).on('resize.autoflip-dropdown', handlePositionChange);
                handlePositionChange();
            })
Exemple #5
0
    beforeRender: function () {
      var fieldClass = _.result(this.view, 'fieldClass');

      if (fieldClass) {
        this.$el.addClass(fieldClass);
      }
    },
Exemple #6
0
    sync_read_collection: function (coll, options) {
        var $this = this;

        var _args = Array.prototype.slice.call(arguments);
        var _super = function () {
            HashSync.prototype.sync_read_collection.apply($this, _args);
        };

        var params = {};
        if (options.limit) {
            params.limit = options.limit;
        }
        
        var design = null;
        if (options.design) {
            design = options.design;
        } else {
            var design_match = /\/(.*)\//.exec(_.result(coll, 'url'));
            design = design_match[1];
        }
        if (!design) { return _super(); } 

        var view = options.view || 'all';

        this.db.view(design, view, params, function (err, body) {
            if (err) { return _super(); }
            var items = body.rows.map(function (item) {
                return {key: item.id, value: item.value};
            });
            options.success($this._sortLimitItems(coll, options, items));
        });
    },
    constructor: function (options) {
      var events = {},
          defaults;

      defaults = {
        dismissOnOverlayClick: false,
        includeCloseButton: false,
        closeButtonClass: 'btn-corner btn-cornerTR',
        innerWrapperClass: 'modal-child modal-childMain custCol-primary'
      };

      this.__options = __.extend({}, defaults, options || {});
      this.className = 'modal modal-opaque ' + __.result(this, 'className', '');
      this._open = false;

      if (this.__options.dismissOnOverlayClick) {
        events['click'] = '__modalClick';
      }

      if (this.__options.includeCloseButton) {
        events['click .js-modal-close'] = '__closeClick';
      }      

      this.events = __.extend({}, events, this.events || {});

      baseVw.prototype.constructor.apply(this, arguments);
    },
Exemple #8
0
    _beforeSaving: function () {
      var value = _.result(this, 'unsavedChange');

      if (value !== undefined) {
        this.model.set(this.name, value);
      }
    },
Exemple #9
0
  delegateEvents: function(events) {
    if (!(events || (events = _.result(this, 'events')))) {
      return;
    }
    // Unbind any current events
    this.undelegateEvents();
    // Event / selector strings
    var keys = _.keys(events);
    var key;
    // Create an array to hold the information to detach events
    this.eventsToRemove = new Array(keys.length);
    for (var i = keys.length; i--;) {
      key = keys[i];
      // Sanity check that value maps to a function
      var method = events[key];
      if (!_.isFunction(method)) {
        method = this[events[key]];
      }
      if (!method) {
        throw new Error('Method "' + events[key] + '" does not exist');
      }
      var match = key.match(delegateEventSplitter);
      var eventName = match[1],
        selector = match[2];
      method = _.bind(method, this);

      // throws an error if invalid
      this.eventsToRemove[i] = tungsten.bindEvent(this.el, eventName, selector, method);
    }
  },
Exemple #10
0
        delegateEvents: function(events) {
            if (!(events || (events = _.result(this, 'events')))) 
                return this;

            for (var key in events) {
                if (events.hasOwnProperty(key)) {
                    var method = events[key];
                    if (!_.isFunction(method))
                        method = this[events[key]];
                    if (!method)
                        continue;

                    var match = key.match(delegateEventSplitter);
                    var eventName = match[1];
                    var displayObject = this[match[2]];

                    if (!(displayObject instanceof PIXI.DisplayObject))
                        throw 'PixiView: this.' + match[2] + ' must be a DisplayObject to bind events on it.';

                    // if (displayObject.hasOwnProperty(eventName))
                    //     throw 'PixiView: ' + eventName + ' is not a valid event.';

                    displayObject[eventName] = _.bind(method, this);
                    displayObject.interactive = true;    
                }
            }

            return this;
        },
Exemple #11
0
 function field_value(field) {
     var value = _.result($(field), 'val');
     if (!_.isUndefined(value)) {
         return value;
     }
     throw new Error(field + ' is not a valid form field!');
 }
        getFieldSignatureSafely: function(fieldId) {
            var signature = null;
            var chain;
            var part;

            if (!fieldId) {
                return signature;
            }

            try {
                chain = this.pathToEntityChain(fieldId);
            } catch (error) {
                this.errorHandler.handle(error);
                return signature;
            }

            part = _.last(chain);
            if (part && part.field) {
                signature = _.pick(part.field, 'type', 'relationType');
                if (_.result(part.field.options, 'identifier')) {
                    signature.identifier = true;
                }
                signature.field = part.field.name;
                signature.entity = chain[chain.length - 2].entity.className;
                if (chain.length > 2) {
                    signature.parent_entity = chain[chain.length - 3].entity.className;
                }
            }

            return signature;
        },
Exemple #13
0
    fetchModels: function() {
        if (!this.isFetching) {
            this.isFetching = true;
            var models = new this.collection();
            var queryString = "";

            // Build the query string if queryParameters have been provided
            if (this.queryParams) {
                queryString = this.buildQueryStringFromQueryParams(
                    this.queryParams
                );
            }

            models
                .fetch({
                    url: _.result(models, "url") + queryString
                })
                .done(
                    function() {
                        this.isFetching = false;
                        this.models = models;
                        if (this.pollingEnabled) {
                            this.models.each(
                                this.pollNowUntilBuildIsFinished.bind(this)
                            );
                        }
                        this.emitChange();
                    }.bind(this)
                );
        }
    },
Exemple #14
0
/** Function: sync
 * This is the core where server side API callbacks are dispatched. This 
 * function replaces Backbone.sync and gets in place during startup
 * (<Barefoot.Startup.Server>).
 *
 * Instead going the detour over an AJAX request, this implementation of sync
 * calls the API callback directly by resolving the models url with the present
 * apiRoutes.
 *
 * Parameters:
 *     (String) method - A method (create, update, patch, delete or read) which
 *                       will be used to resolve the models url properly.
 *     (Backbone.Model) model - The model which wants to be synced. Can also be
 *                              an instance of Backbone.Collection.
 *     (Object) options - Should contain at least a success callback. Any api
 *                        callback result will be delivered as argument of the
 *                        success function.
 */
function sync(method, model, options) {
	var url = options.url || _.result(model, 'url')
		, apiPrefix = getAPIPrefix()
		, httpMethod = methodMap[method];

	if(_.isUndefined(url)) {
		throw new Error('No url present for syncing!', model, options);
	}

	if(url.substr(0, apiPrefix.length) === apiPrefix) {
		url = url.substr(apiPrefix.length);
	}

	var apiRouteCallback = this.apiRoutes[httpMethod][url]
		, apiResult
		, error;

	if(_.isUndefined(apiRouteCallback)) {
		throw new Error('Could not resolve API route: ' + url);
	}

	try {
		apiResult = apiRouteCallback();
	} catch(err) {
		error = err;
	}

	if(!error) {
		if(options.success) { options.success(apiResult); }
	} else {
		if(options.error) { options.error(error); }
	}
}
Exemple #15
0
 BaseComponent = function(options) {
     this.cid = _.uniqueId(this.cidPrefix);
     _.extend(this, _.pick(options, _.result(this, 'optionNames')));
     _.extend(this, options[BaseComponent.RELATED_SIBLING_COMPONENTS_PROPERTY_NAME]);
     this.initialize(options);
     this.delegateListeners();
 };
Exemple #16
0
 defaults: function () {
   return _.extend(_.result(Command.prototype, 'defaults'), {
     command: 'sass',
     paths: [process.cwd()],
     ext: 'css'
   });
 },
 getDefaultTime: function() {
     var date;
     var todayDate;
     var currentTimeMoment;
     var guessTimeMoment;
     var time = _.result(this, 'defaultTime');
     if (!time) {
         date = this.$frontDateField.val();
         todayDate = moment().tz(this.timezone).format(this.getDateFormat());
         if (date === todayDate) {
             currentTimeMoment = moment().tz(this.timezone);
             // add 15 minutes to current time if it's today date
             guessTimeMoment = currentTimeMoment.clone().add(15, 'minutes');
             // round up till 5 minutes
             guessTimeMoment.add(5 - (guessTimeMoment.minute() % 5 || 5), 'minutes');
             if (guessTimeMoment.diff(currentTimeMoment.clone().set('hour', 23).set('minute', 59)) < 0) {
                 // if it is still same date
                 time = guessTimeMoment.format('HH:mm');
             } else {
                 // set max available time for today
                 time = '23:59';
             }
         } else {
             // default time is beginning of the day
             time = '00:00';
         }
     }
     return moment(time, 'HH:mm').format(this.getTimeFormat());
 },
Exemple #18
0
	setElement: function(element) {
		var ret = this._super(element);
		if(this.template) {
			this.$el.html(_.result(this, 'template'));
		}
		return ret;
	},
 events: function() {
     var events = _.defaults({
         'click .dashboard-picker-collapse': '_toggleWidget',
         'click .add-widget-button': '_onClickAddToDashboard'
     }, _.result(WidgetPickerModal.__super__, 'events'));
     return events;
 },
    it('Should set default options for the grid', function (done) {
        var options = {};

        expect(_.has(options, 'sortConfig')).to.be.false;
        expect(_.has(options, 'id')).to.be.false;
        expect(_.has(options, 'rows')).to.be.false;
        expect(_.has(options, 'stateManager')).to.be.false;
        expect(_.has(options, 'addListeners')).to.be.false;
        expect(_.has(options, 'borders')).to.be.false;
        expect(_.has(options, 'treeMode')).to.be.false;
        expect(_.has(options, 'childData')).to.be.false;
        expect(_.has(options, 'launchLinksNewTab')).to.be.false;

        new Grid(options);

        expect(options.sortConfig).to.have.length(0);
        expect(options.id).to.equal('id');
        expect(options.rows.link).to.be.false;
        expect(options.rows.newRow).to.be.false;
        expect(options.rows.totalRow).to.be.false;
        expect(_.result(options.stateManager, 'isEditable')).to.be.false;
        expect(_.has(options, 'addListeners')).to.be.true;
        expect(options.borders).to.be.true;
        expect(options.treeMode).to.be.false;
        expect(options.launchLinksNewTab).to.be.false;

        options.childData().done(function (collection) {
            expect(collection).to.have.length(0);
            done();
        });

    });
Exemple #21
0
  _mostPrivilegedGroupAclItem: function (m) {
    var groups = _.result(m.groups, 'models');

    if (groups) {
      return this._findMostPrivilegedAclItem(groups, this._ownAclItem);
    }
  },
Exemple #22
0
      sync: function(method, model, options) {
        // Parse query string from the params object property
        var params = this.get("params");
        var queryString = "";
        for (var i in params) {
          if (params.hasOwnProperty(i)) {
            queryString += "&"+i+"="+params[i];
          }
        }
        queryString = queryString.substr(1,queryString.length);

        // override sync
        var _sync = Backbone.sync;
        var deferred = $.Deferred();
        if (method === 'read') {
          // use the request module instead of jQuery so we can do serverside cross-domain access
          request({
            url : _.result(model, 'url')+options.command+"?"+queryString+"&api_key="+APIKEY
          }, function(error, response, body) {
            if (!error && response.statusCode === 200) {
              options.success(model, body, options);
              deferred.resolve(model);
            }
            else {
              options.error(model, response, options.BBoptions);
              deferred.reject(model);
            }
          });

          return deferred.promise();
        }
        else {
          return _sync.apply(this, arguments);
        }
      },
Exemple #23
0
      this.structure.each(function (column) {
        // This column interface won't be rendered
        // or submitted
        if (this.omitInput(column)) {
          return;
        }

        if (model.isReadBlacklisted && model.isReadBlacklisted(column.id)) {
          return false;
        }

        // Skip magic owner column if we dont have bigedit
        if (table && table.get('user_create_column') === column.id && !model.collection.hasPermission('bigedit')) {
          return;
        }

        var inputOptions = {
          structure: this.structure,
          inModal: this.inModal
        };

        if (column.get('key') === 'PRI') {
          inputOptions.canWrite = false;
        }

        var view = UIManager.getInputInstance(model, column.id, inputOptions);
        if (model.addInput) {
          model.addInput(column.id, view);
        }

        // Display:none; hidden fields
        // forcing interface-based visibility
        var visibility = _.result(view, 'visible');
        var isHidden = Utils.isSomething(visibility) ? !visibility : _.contains(this.hiddenFields, column.id);
        if (_.contains(this.forceVisibleFields, column.id)) {
          isHidden = false;
        }

        if (isHidden) {
          view.$el.css({'display':'none'});
        }

        if (view.isRequired()) {
          view.$el.addClass('required');
          column.set('required', true);
        }

        if (!isHidden) {
          var uiContainer = new UIContainer({
            model: model,
            column: column,
            batchEdit: isBatchEdit,
            view: view
          });
          uiContainer.insertView('.interface', view);
          views[column.id] = uiContainer;
        } else {
          this.insertView('.fields',view);
        }
      }, this);
 getViewOptions: function() {
     return $.extend(true, {}, _.result(this.metadata, 'view_options', {}), {
         autoRender: true,
         model: this.model,
         fieldName: this.fieldName
     });
 },
Exemple #25
0
    fs.readFile(path.join(__dirname,"../templates/default.us"),  "utf-8", function (err, data) {
      var name = _.result(options, "name") || path.basename(path.resolve("."));

      if(err) return cb(err);
      options.logger.info("Writing file " + path.join(location, (stageName || "deploy")+".js"));
      fs.writeFile(path.join(location, (stageName || "deploy")+".js"), _.template(data)({name: stageName, app_name: name, repository_url: "giturl"}), cb);
    });
Exemple #26
0
	this.getItem = function(model, options) {
		var params = {DomainName: model._domainName()},
			idAttrName = _.result(model, 'idAttribute'),
			attrSchema = model._attributeSchema(idAttrName);
		params.ItemName = _.isString(model.id) || !attrSchema ? model.id : this.encode(model.id, attrSchema);

		_.extend(params, options.sdb);
		
		// If a 'close' event was fired on the SimpleDB HTTP request, the callback might be called twice,
		// therefore, the callback is forced to run only once.
		// A 'close' can be fired after 'end': http://nodejs.org/docs/latest/api/http.html#event_end_
		sdb.request('GetAttributes', params, _.once(_.bind(function(error, response) {
			// A 'close' event triggers an error, but a 'close' event doesn't mean that the request failed.
			// Checking the HTTP response code.
			if (error && error.code !== 200 && error.code !== 204) options.error(model, {code: 'DBError', sdb: error});
			else {
				var attrs = null;
				try {
					attrs = response.GetAttributesResult.Attribute;
					if (_.isEmpty(attrs)) throw 'Not found';
					_.isArray(attrs) || (attrs = [attrs]);
				} catch (e) {
					attrs = null;
					options.error(model, {code: 'NotFound', sdb: response});
				}

				if (attrs) options.success({model: this.parseAttributes(model, attrs), sdb: response});
			}
			
			if (_.isFunction(options.complete)) options.complete(model, {sdb: response});
		}, this)));
	};
    _bind_before_filters: function(options) {

        this.before_filters = _.result(this, 'before_filters');

        if (this.before_filters) {
            //internal express router that will be used to organize before filters
            //and used in middleware chain
            this._express_filter_router = express.Router({
                caseSensitive: options.caseSensitive || false,
                strict: options.strict || false,
                mergeParams: options.mergeParams || false
            });

            var self = this;

            Object.keys(this.before_filters).forEach(function beforeFilter(beforeFilter) {

                var method = beforeFilter.split('|')[1] || 'get';
                var url = beforeFilter.split('|')[0];

                self._express_filter_router[method]('/' + url, function(request, response, next) {
                    self._get_filter(beforeFilter)(request, response, next);
                });
            });
        }
    }
Exemple #28
0
        dispose: function() {
            if (this.disposed) {
                return;
            }
            this.trigger('dispose', this);
            this.unsubscribeAllEvents();
            this.stopListening();
            this.off();
            var siblingComponents = _.keys(BaseComponent.getRelatedSiblingComponentNames(this.constructor));
            var optionNames = _.result(this, 'optionNames');

            // dispose and remove all own properties
            _.each(this, function(item, name) {
                if (optionNames.indexOf(name) !== -1 || siblingComponents.indexOf(name) !== -1) {
                    /**
                     * Do not dispose auto-assigned props, that were passed over options or sibling components.
                     * Just delete a reference.
                     * Parent view or component have to take care of them, to dispose them properly.
                     */
                    delete this[name];
                    return;
                }
                if (item && typeof item.dispose === 'function' && !item.disposed) {
                    item.dispose();
                }
                if (['cid'].indexOf(name) === -1) {
                    delete this[name];
                }
            }, this);
            this.disposed = true;

            return typeof Object.freeze === 'function' ? Object.freeze(this) : void 0;
        },
Exemple #29
0
  newView: function(view, bodyID, addressBarText, bodyClass){
    var loadingConfig;

    this.cleanup();
    //clear address bar. This will be replaced on the user page
    addressBarText = addressBarText || "";
    window.obEventBus.trigger("setAddressBar", addressBarText);

    if($('body').attr('id') != bodyID){
      $('body').attr("id", bodyID || "");
    }
    if(bodyClass){
      $('body').attr('class', bodyClass);
    }
    $('#obContainer').removeClass("box-borderDashed noScrollBar overflowHidden"); //remove customization styling if present
    
    this.pageConnectModal && this.pageConnectModal.remove();
    this.pageConnectModal = null;

    if (
      (loadingConfig = __.result(view, 'loadingConfig')) &&
      loadingConfig.promise &&
      typeof loadingConfig.promise.then === 'function') {
      this.launchPageConnectModal(loadingConfig);
    }
    
    this.view && (this.view.close ? this.view.close() : this.view.remove());
    this.view = view;

    $('#obContainer')[0].scrollTop = 0;
  },
Exemple #30
0
 query: function() {
   this._builder || (this._builder = this.builder(_.result(this, 'tableName')));
   var args = _.toArray(arguments);
   if (args.length === 0) return this._builder;
   this._builder[args[0]].apply(this._builder, args.slice(1));
   return this;
 },