Exemplo n.º 1
0
    initialize: function (opts={}) {
        this.key = _key();
        _modals[this.key] = this;

        this.id = `modalWindow:${this.key}`;
        this.isOpen = false;
        this.closable = !!opts.closable;
        this.disposeOnClose = !!opts.disposeOnClose;

        if (opts.title) {
            this.title = opts.title;
        }

        this.init(opts);

        _.bindAll(
            this,
            'render', 'dispose', 'close', 'open', '_close', 'isActive',
            'content', 'init', 'afterRender'
        );

        this.render();
        this.afterRender();
    },
Exemplo n.º 2
0
    initialize: function(options) {
        _.bindAll(
            this, 'render', 'maybeEnableNext', 'beforeUnload',
            'onComplete', 'onPrint', 'onStep');
        this.template = require('../static/templates/steps-template.html');
        this.steps = new StepCollection();

        for (var i = 0; i < options.views.length; i++) {
            var view = options.views[i];
            var step = new Step({view: view, idx: i, id: view.cid});
            step.bind('change:complete', this.render);
            this.steps.add(step);
            options.views[i].once('complete', this.onComplete, [view]);
        }

        this.currentStep = new CurrentStep();
        this.currentStep.bind('change', this.render);
        this.currentStep.set('idx', 0);

        var quiet = getUrlParameter('quiet') === '1';
        if (!quiet) {
            jQuery(window).on('beforeunload', this.beforeUnload);
        }
    },
Exemplo n.º 3
0
  initialize: function (options) {
    _.bindAll(this, 'toggleSearch')

    this.litewrite = options.litewrite

    this.editor = new EditorView({ model: this.model })
    this.search = new SearchView({ model: this.litewrite.state })
    this.aside = new AsideView({ model: this.model, collection: this.collection })
    this.entries = new EntriesView({ litewrite: this.litewrite, collection: this.collection })
    this.date = new DateView({ model: this.model })
    var share = new ShareView({ model: this.model, collection: this.collection })

    this.litewrite
      .on('ready', this.editor.render)
      .on('ready', this.editor.desktopFocus)
      .on('ready', this.aside.desktopHide)
      .on('connected', share.show)
      .on('disconnected', share.hide)

    this.collection
      .on('add', this.toggleSearch)
      .on('remove', this.toggleSearch)

    this.search
      .on('focus', this.aside.show)
      .on('blur', this.editor.desktopFocus)
      .on('blur', this.aside.desktopHide)

    // this way we don't hide the sidebar while search is focusesd
    this.editor
      .on('typing', this.aside.desktopHide)

    this.entries
      .on('open', this.editor.desktopFocus)
      .on('open', this.aside.hide)
  },
Exemplo n.º 4
0
  initialize: function (options) {
    _.bindAll(this, 'open', 'hide', '_handleClick', '_keydown', '_onDocumentClick');

    this.options = {};
    // Extend options
    _.defaults(this.options, options, DEFAULTS);

    if (options.template) {
      this.template = options.template;
    }

    // Bind to target
    $(options.target).on('click', this._handleClick);
    $(document).on('keydown', this._keydown);
    $(document).on('click', this._onDocumentClick);

    this.modelView = new Backbone.Model({
      open: false
    });

    this.modelView.on('change:open', function (model, isOpen) {
      isOpen ? this.hide() : this.open();
    }, this);
  },
Exemplo n.º 5
0
    initialize: function(options) {
        options = options || {};
        _.bindAll(this, 'renderTick', 'onFuncChanged');

        this.paused = false;

        this.curveFuncs = options.curveFuncs;
        this.curveFuncs.on('FuncChanged', this.onFuncChanged)

        this.initialX = options.initialX || 0;
        this.resetInitialX = options.resetInitialX || 0;
        this.backgroundColor = options.backgroundColor || '#000';
        this.intervalWidth = options.intervalWidth || 15;

        this.segments = [];
        this.initSegment(this.initialX);
        
        this.xStep = 1;

        this.displayInterval = options.displayInterval || 1200;
        this.displayIntervalAnchor = options.displayIntervalAnchor || Date.now();

        this.lastBackgroundState = null;
        this.currentX = this.initialX;

        this.leftSegmentPos = 0;
        this.rightSegmentPos = 1;

        this.intervalCtr = 0;

        this.anchorTime = Date.now(); // May be any time
        this.refTime = Date.now(); // Always now

        this.renderTickInterval = 50;
        this.renderTick();
    },
/**
 * @constructor
 * @param {!Object} obj 
 */
function Response(obj) {
  this.error_ = obj.error || Response.default.error;

  this.status_ = obj.status || Response.default.status;

  this.data_ = !_.isUndefined(obj.data) ? obj.data : Response.default.data;
  
  this.raw_ = !_.isUndefined(obj.raw) ? obj.raw : Response.default.raw;
  
  this.buffer_ = !_.isUndefined(obj.buffer) ? obj.buffer : Response.default.buffer;

  _.bindAll(this);

  var public_ = {
    getError: this.getError,
    getStatus: this.getStatus,
    getData: this.getData,
    getRaw: this.getRaw,
    getBuffer: this.getBuffer,
    isOk: this.isOk
  }

  return public_;
}
Exemplo n.º 7
0
function Server(goals){

  var self = this;

  this._goals = goals;
  this._server = simplesmtp.createSimpleServer({}, function(req){
    var email = '';

    req.on('data', function(data){
      email += data;
    });

    req.on('end', function(){
      self._handleEmail(email, function(err){
        req.accept();
        var status = err ? 'failed': 'handled';
        logger.log('Email from ' + req.from + ': ' + status);
      });
    });
  })

  _.bindAll(self);

}
Exemplo n.º 8
0
  initialize: function (init) {
    _.bindAll(this)
    var self = this;
    this.model = init || new Backbone.Model()

    this.$el.html(template(this.model.toJSON()))

    this.render()
    // deffered to properly initialize CodeMirror
    _.defer(function () {
      var cm = CodeMirror.fromTextArea(this.$('#code')[0], {
        lineNumbers: true,
        indentUnit: 2,
        tabSize: 2,
      });

      cm.on('change', function() {
        self.model.set({code: cm.getValue()})
      })
    })

    this.model.on('change:result', this.render)

  },
Exemplo n.º 9
0
 create: function (attributes) {
     
     attributes = attributes || {};
     
     var self = this,
         instanceOwnProperties = {
             schema: self.schema,
             connection: self.connection,
             attributes: {},
             Model: this
         },
         reserved = ['options', 'schema', 'connection', 'client', 'attributes', 'Model'];
     
     _.each(self.options, function(val, key){
         if (reserved.indexOf(key) >= 0) return;
         instanceOwnProperties[key] = val;
     });
     
     _.each(self.schema.attributes, function(type, attr){
         attributes[attr] = attributes[attr];
     });
     
     return _.bindAll(Object.create(model, helper.ownProperties(instanceOwnProperties)).set(attributes));
 },
        initialize: function(options) {
            _.bindAll(this, "onGlobalMouseup", "onGlobalMousedown", "onResize", "onGlobalMousemove",
                "onMousedown", "onMouseup", "onEscKey", "onSelectAll", "onSelectNone",
                "onInvertSelection");

            this._debouncedOnResize = _.debounce(this.onResize, 500);

            if (!this.model) {
                this.model = new Backbone.Model();
            }

            this.model.set("criteria", "", {silent: true});

            this.label = options.label;
            this.template = _.template(options.availableItemsTemplate || availableItemsTabTemplate);

            this.keyboardManager = new KeyboardManager({
                keydownHandlers: this.keydownHandlers,
                keydownTimeout: options.keydownTimeout,
                context: this,
                deferredKeydownHandler: this.processKeydown,
                immediateHandleCondition: this.immediateHandleCondition,
                immediateKeydownHandler: this.immediateKeydownHandler,
                stopPropagation: true
            });

            this.listViewModel = this._createListViewModel(options);

            this.setValue(options.value, {silent: true});

            this.listView = this._createListView(options);

            this.render();

            this.initListeners();
        },
Exemplo n.º 11
0
  initialize: function(models, options) {
    _.bindAll(this);

    this.repo = options.repo;
    this.branch = options.branch;
    this.sha = options.sha;

    // Sort files reverse alphabetically if path begins with '_posts/'
    this.comparator = function(a, b) {
      var typeA = a.get('type');
      var typeB = b.get('type');

      var pathA = a.get('path');
      var pathB = b.get('path');

      var regex = /^_posts\/.*$/

      if (typeA === typeB && typeA === 'file' && regex.test(pathA) && regex.test(pathB)) {
        // Reverse alphabetical
        return pathA < pathB ? 1 : -1;
      } else if (typeA === typeB) {
        // Alphabetical
        return pathA < pathB ? -1 : 1;
      } else {
        switch(typeA) {
          case 'tree':
          case 'folder':
            return -1;
            break;
          case 'file':
            return typeB === 'folder' || typeB === 'tree' ? 1 : -1;
            break;
        }
      }
    };
  },
Exemplo n.º 12
0
 initialize: function (options) {
     _.bindAll(this, "render");
     var controller = options.controller;
     this.AdView = require("./AdView.js");
     this.model.bind("sync", function (model) {
         this.render(controller.getModelItems(model));
         this.createNew();
         this.updateStatus();
     }.bind(this));
     var FormView = require("./FormView.js"),
         AdModel = require("../models/AdModel.js"),
         self = this;
     this.form = new FormView({
         model: new AdModel(),
         controller: controller,
         events: {
             "click .ctrl": function (e) {
                 e.preventDefault();
                 var form = this;
                 controller.makeAction(e.target.name.split(" ")[0], form.model, self.model);
             }
         }
     });
 },
Exemplo n.º 13
0
        initialize: function (parentContext) {
            //create module context by assiciating with the parent context
            var self = this,
                context = new Boiler.Context(parentContext);
            _.bindAll(this, 'startMigration', 'onRenderSettingView', 'onRateApp');
            context.addSettings(settings);
            templates.load(settings);
            context.listen(window.app.Events.RateApp, this.onRateApp);
            window.app.baseModule = {
                context: context,
                renderSettingView: this.onRenderSettingView,
                settingModel: settingModel,
            };
            localStorage.on('change:migrated', this.onMigrationComplete, this);
            settingModel.fetch();
            setTimeout(function () {
                localStorage.fetch({
                    success: self.startMigration,
                    //First time if localstorage it not there it will fail
                    error: self.startMigration
                });

            });
        },
Exemplo n.º 14
0
 var Pool = function(config, client) {
   _.bindAll(this, 'acquire', 'release');
   this.config = config;
   this.client = client;
   this.init();
 };
Exemplo n.º 15
0
 constructor: function (options) {
     _.bindAll(this, '_loadRegions');
     this.regions = _.extend({}, _.result(this, 'regions'));
     View.apply(this, arguments);
 },
Exemplo n.º 16
0
 constructor: function (options) {
     _.bindAll(this, 'addRegions');
     _.extend(this, _.pick(options, ['channelName']));
     this.channelName || (this.channelName = _.uniqueId('channel'));
     Object.apply(this, arguments);
 },
Exemplo n.º 17
0
 constructor: function (options) {
     options || (options = {});
     _.bindAll(this, 'show', 'remove');
     _.extend(this, _.pick(options, ['$el']));
     Object.apply(this, arguments);
 },
Exemplo n.º 18
0
import _ from 'underscore';
import Backbone from 'backbone';
const SelectComponent = require('./SelectComponent');
const $ = Backbone.$;

module.exports = _.extend({}, SelectComponent, {
  init(o) {
    _.bindAll(this, 'startDelete', 'stopDelete', 'onDelete');
    this.hoverClass = this.pfx + 'hover-delete';
    this.badgeClass = this.pfx + 'badge-red';
  },

  enable() {
    var that = this;
    this.$el
      .find('*')
      .mouseover(this.startDelete)
      .mouseout(this.stopDelete)
      .click(this.onDelete);
  },

  /**
   * Start command
   * @param {Object}  e
   * @private
   */
  startDelete(e) {
    e.stopPropagation();
    var $this = $(e.target);

    // Show badge if possible
Exemplo n.º 19
0
		initialize: function(options) {
			options || (options = {});
			_.defaults(this, this.defaults);
			_.extend(this, _.pick(options, _.keys(this.defaults)));
			_.bindAll(this, "close");
		},
Exemplo n.º 20
0
function World(options){
  _.bindAll(this, 'add', 'bindTo', 'draw', 'run', 'render', 'detectCollisions', 'eachProp', 'inBounds', 'remove');
  this.props = [];
  this.height = options.height;
  this.width = options.width;
}
Exemplo n.º 21
0
var func = function (greeting) {
    return greeting + ': ' + this.name;
};
func = _.bind(func, { name: 'moe' }, 'hi');
func();

var buttonView = {
    label: 'underscore',
    onClick: function () {
        alert('clicked: ' + this.label);
    },
    onHover: function () {
        console.log('hovering: ' + this.label);
    }
};
_.bindAll(buttonView);
$('#underscore_button').bind('click', buttonView.onClick);

var fibonacci = _.memoize(function (n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');

_.defer(function () {
    alert('deferred');
});

var updatePosition = function () {
    return alert('updating position...');
Exemplo n.º 22
0
	initialize: function(){
		_.bindAll(this, 'updateGain');
		this.on('change:gain', this.updateGain);
		this.on('change:step', this.updateGain);
		this.updateGain();
	},
Exemplo n.º 23
0
import Direction from '../level/direction';

//import BasicRenderer from '../level/render/basic-renderer';
import InvaderRenderer from '../level/render/invader-renderer';

let GameView = Marionette.ItemView.extend({
    className: 'game',
    template: require('../templates/game.mustache'),
    ui: {
        field: '.game-field'
    },
    initialize(options) {
        this._app = options.app;
        this._game = null;

        _.bindAll(this, 'onKeyDown', 'onKeyUp', 'onTouchStart', 'onTouchEnd');
    },
    initializeListeners() {
        let app = this._app;

        this.listenTo(this._game, 'levelSet:load', (levelSet, source) => {
            this._app.vent.trigger('game:levelSet:load', levelSet, source);
        });

        this.listenTo(this._game, 'level:number', levelNumber => {
            app.vent.trigger('game:level:number', levelNumber);
        });

        this.listenTo(this._game, 'level:move:start', stats => {
            app.vent.trigger('game:level:move:start', stats);
        });
Exemplo n.º 24
0
 initialize: function() {
   _.bindAll(this);
   this.brand = new BrandView({ model: this.model });
   this.collection.bind('change', this.render);
   this.render();
 },
Exemplo n.º 25
0
  var Store = function(namespace){
    _.bindAll(this);

    this.namespace = namespace || 'book:store:default';
  };
Exemplo n.º 26
0
    async = require('async'),
    shell = require('shelljs'),
    path = require('path'),
    fs = require('fs'),
    _ = require('underscore'),
    readdirp = require('readdirp'),
    Q = require('q'),
    deferred = Q.defer(),
    add_error_messages = require('./utils/add_error_messages'),
    output_path = require('./utils/output_path'),
    Compiler = require('./compiler');

// initialization and error handling

var compiler = new Compiler();
_.bindAll(compiler);

compiler.on('error', function(err){
  console.log('\u0007'); // bell sound
  console.error("\n\n------------ ERROR ------------\n\n".red + err + "\n");
  add_error_messages.call(this, err, this.finish);
});

// @api public
// Given a root (folder or file), compile with roots and output to /public

exports.compile_project = function(root, done){

  compiler.once('finished', function(){
    process.stdout.write('done!\n'.green);
    done();
Exemplo n.º 27
0
 constructor: function (options)
 {
     _.bindAll(this);
     Document.prototype.constructor.apply(this, arguments);
     this.options = options || {};
 },
Exemplo n.º 28
0
var Api = function() {
  _.bindAll( this )
}
Exemplo n.º 29
0
function Cluster(clusterID, contexts, options, config) {
    this.clusterID = clusterID;

    _.bindAll(this, 'dataChanged', 'dataAdded', 'dataCleared', 'render');
    this.dataChanged = _.debounce(this.dataChanged, 50);

    this.initCollection(contexts);

    this.defaultConfig = {
        scaleFactor: 0.7,
        spaceFactor: 0.7,
        minDepth: 2,
        maxDepth: null,
        layoutChange: true,
        hideLabels: false,
        labelIDsOnly: false,
        hideChildren: false,
        childAngleArc: 180,
        focusAngleArc: 360,
        focusStartAngle: 30,
        focusFontSize: 1.3,
        fadeDepth: 3,
        fadeFactor: 0.25,
        fadeTarget: options.baseBGColor || '#fff',
        fontFraction: 0.22,
        fontSizeProportion: 0.05,
        hideSmallText: true,
        baseZIndex: 20000,
        numDetailLevels: 5,
        animateDuration: 400,
        hideDuration: 325,
        noCompress: false,
        labelFunc: null,
        forceFocusStartAngle: false,
        childLimit: null,
        newContextBumpTime: 10 * 60,  // 10 minutes
        dropDisabled: false,
        dragDisabled: false,
        moveDisabled: false,
        showDetailIndicator: true,
        setBackgroundFilterLevel: true,
        visualQuality: options.visualQuality || 0, // 0 to 1
        allowRootOnly: false,
        filterType: 'cutoff',
        filterOptions: {
            cutoffValue: 0.2
        }
    }

    this.state = {};
    this.viewCache = {};
    this.focusData = {};
    this.viewStates = {};

    this.setConfig(config);

    this.listeners = options.listeners || {};
    this.$container = options.$el;
    this.filterLevel = options.filterLevel || 0;
    this.minLightness = options.minLightness;
    this.baseBGColor = options.baseBGColor || '#fff';
    this.fontSize = options.fontSize;
    this.globalRootContextID = options.globalRootContextID;
    this.debounceRender = _.debounce(this.render, 250);

    var rootID = this.contexts.rootID,
        focusID = options.focusID || rootID;

    this.colors = new Colors(this.contexts, {
        rootContextID: rootID,
        minLightness: this.minLightness
    });

    this.defaultNodeAppearance = {
        getColor: _.bind(this.colors.getColor, this.colors)
    };
    this.nodeAppearance = this.defaultNodeAppearance;

    this.init(rootID, focusID);
}
Exemplo n.º 30
0
function TheRock(id) {
	
	if (id) {
					this.username = id.username;
					this.password = id.password;
					this.api_key = id.api_key;
	}
	
	this.id =  this.api_key && this.username && this.password ? true:false
	
	this.apiURL = 'https://www.therocktrading.com/api/'
	

	this.offers = [];
	this.trades = [];
	this.funds = false;
	this.balance = {};
	
	this.reconnectINTERVAL = 5; //seconds       // time interval before trying to reconnect on start-up
	this.reconnectMAX = 5;								// max number of reconnections before emitting an error
	this.monitorINTERVAL = 2 //seconds				// monitoring rate
	this.monitorMAXerrors = 30;						// max number of monitor error before emitting an error
	this.tradesLength = 200;
	
	this.timeoutINTERVAL = 7;
	this.bookINTERVAL = 2;
	this.tradesINTERVAL = 2;	
	this.bookMAXerrors = 30;
	this.tradesMAXerrors = 30;

	
	this.reconnectTRY = 0;
	this.reconnectTRY_subscribe = 0;
	this.monitorErrors = 0;
	this.monitoring = false;
	this.periodic = true;
	
		
	_.bindAll(this,'privreq','pubreq','tickers', 'checkTrades', 'orderbook', 'getBalance','getOrders', 'placeOrder', 'cancelOrder' )
	_.bindAll(this,'start', 'stop', 'monitor', '_monitor','watch', 'set', 'subscribe', 'unsubscribe')
	
	var self = this

	this.on('start', function(){
		self.monitor();	
	})
	
	this.on('trade', function(trade){
		self.trades.push(trade)
		var inpiu = self.trades.length - self.tradesLength;
		if (inpiu > 0) self.trades.splice(0, inpiu)
	})
	
	this.on('orderCancelled', function(id){
		for (i=0; i<self.offers.length; i++) {
			if (self.offers[i].order_id == id) {
					self.offers.splice(i,1)			
			}		
		}	
	})	
	
	
	this.on('orderPlaced', function(params){
		self.offers.push({
			id: params.id,
			fund_name: params.fund_name,
			type: params.order_type,
			price: params.price,
			amountOpen: params.amount,
			amountUnfilled: params.amount
		})	
	})
	

}