示例#1
0
文件: pool.js 项目: stesla/wsclient
function pooledSocket(socket) {
  var count = 0;
  socket.connect = _.wrap(socket.connect, function(f) {
    if (count === 0) { f.apply(socket, []); }
    count++;
  });
  socket.close = _.wrap(socket.close, function(f) {
    count--;
    if (count === 0) { f.apply(socket, []); }
  });
  return socket;
}
示例#2
0
			_.each(extractedMouseEvents, function (extractedMouseEvents, target) {
				_.each(mouseEvents, function (mouseEvent) {
					originalEventFunctionOrString = extractedMouseEvents[mouseEvent];

					mouseFunctions[mouseEvent] = getProperty(protoProps, events[originalEventFunctionOrString]);

					delete events[originalEventFunctionOrString];
				});

				events[addTargetToEventName("touchstart", target)] = _.wrap([mouseFunctions["mouseenter"], mouseFunctions["mousedown"]], touchstartWrapper);
				events[addTargetToEventName("touchmove", target)] = _.wrap(mouseFunctions["mousemove"], touchmoveWrapper);
				events[addTargetToEventName("touchend", target)] = _.wrap([mouseFunctions["mouseup"], mouseFunctions["mouseleave"], mouseFunctions["click"]], touchendWrapper);
			});
示例#3
0
module.exports = function(client) {
	'use strict';

	client.on('network raw:privmsg', glue);
	client.on('network raw:notice', glue);
	client.on('network raw:quit', glue);
	client.on('network raw:mode', _.wrap(gotSelf, glue));
	client.on('network raw:nick', _.wrap(gotSelf, glue));

	client.on('network disconnect', function(event) {
		event.network.users.forEach(function(user) {
			user.set('mode', undefined);

			user.channels.forEach(function(channel) {
				channel.set('joined', false);
				channel.set('mode', undefined);
			});
		});
	});

	client.on('network user raw:nick', function(event) {
		event = _.clone(event);
		event.old = event.user.get('name');
		event.new = event.params[0];
		event.user.set('name', event.params[0]);
		event.user._name = event.params[0].toLowerCase();
		event.user.emit('nick', event);
	});

	client.on('network user raw:quit', function(event) {
		event = _.clone(event);
		event.text = event.params[event.params.length - 1];
		event.user.emit('quit', event);
	});

	// TODO: CTCP
	client.on('network user raw:privmsg', function(event) {
		event = _.clone(event);
		event.text = event.params[event.params.length -1];
		event.user.emit('message', event);
	});

	client.on('network user raw:notice', function(event) {
		event = _.clone(event);
		event.text = event.params[event.params.length -1];
		event.user.emit('notice', event);
	});
};
示例#4
0
        _.each(this.routes, function (value, key) {
            var callback = this[value],
                route = {},
                path;

            if (!_.isFunction(callback)) {
                throw "route function `" + value + "` not found";
            }

            var wrapper = _.wrap(callback, function () {
                var args = (arguments[1] && route.route.exec(arguments[1])) || [];
                args.shift();
                // allow for beforeRoute to stop the route
                if (_this._handleBeforeRoute.apply(_this, args) !== false) {
                    callback.apply(_this, args);
                    _this._handleAfterRoute.apply(_this.args);
                } else {
                    // fix to the previous url.
                }

            });
            path = (key.length > 0) ? this.path + "/" + key : this.path;
            route.key = key;
            route.route = this._routeToRegExp(path);
            route.callback = wrapper;
            route.score = path.split(':').length - 1;

            this.routes[key] = route
        }, this);
示例#5
0
module.exports = function(ngin) {
  var Model = ngin.Model
  var config = ngin.config

  /**
   * Subvenue Class
   *
   * @param {Object} attr
   * @param {Object} options
   * @api public
   */

  var Subvenue = Model.extend({

    urlRoot: function(options) {
      options = options || {}
      var venueID = options.venue_id || this.venue_id
      this.venue_id = venueID
      delete options.venue_id

      var base = config.urls && config.urls.venues || config.url
      return Url.resolve(base, '/venues/' + this.venue_id + '/subvenues')
    }

  })

  // wrap the inheirited list function with arg checking
  Subvenue.list = _.wrap(Subvenue.list, function(list, options, callback) {
    if (!options.venue_id) return callback(new Error('venue_id is required'))
    list.call(Subvenue, options, callback)
  })

  return Subvenue

}
示例#6
0
		mockCursor[key] = function () {
			var args = _.toArray(arguments);
			
			//Wrap callback
			if (_.isFunction(_.last(args))) {
				args[arguments.length - 1] = _.wrap(_.last(args), function (callback, err, objects) {
					if (err || objects.length === 0)
						return callback(err, objects);

					if (!_.isUndefined(objects)) {
						async.map(objects, function (object, modelCallback) {
							//Also automatically call retrieved() on returned instance
							var model = new (Platos[object._model] || Model)(object);
							delete model._model;

							//Create arguments for calling retrieved
							var retArgs = [ function () {
								modelCallback(null, model);
							} ];

							//Tenant is only passed when necessary
							if (tenant)
								retArgs.splice(0, 0, tenant);

							model.retrieved.apply(model, retArgs);
						}, callback);
					}
				});
			}
			
			cursor[key].apply(cursor, args);
			
			return mockCursor;
		};
示例#7
0
function initLogLevel() {
  log.init();

  let level = 'INFO';
  if (process.argv.indexOf('-v') >= 0) level = 'DEBUG';
  if (process.argv.indexOf('-vv') >= 0) level = 'TRACE';

  // print HTTP details in TRACE
  if (level === 'TRACE') {
    const request = require('request');
    request.debug = true;

    console.error = _.wrap(console.error, function(func) {
      let args = Array.from(arguments);
      args.shift();

      // FIXME: hack HTTP request log, hope no one else use it...
      if (args.length > 0 && args[0].indexOf('REQUEST ') === 0) {
        args = args.map((x) => h.printSafeHTTP(x));
        log.trace.apply(log, args);
      } else {
        log.info.apply(log, args);
      }
    });
  }

  log.setLevel(level);
}
示例#8
0
文件: index.js 项目: lizzz0523/Zoe
        slideTo : function(index, next, callback) {
            var items = this.items,
                curIndex = this.curIndex,
                type;

            if (_.isBoolean(next) ? next : index > curIndex) {
                type = ZSlider.TYPE_NEXT;
                this.append(items[index].el);
            } else {
                type = ZSlider.TYPE_PREV;
                this.prepend(items[index].el);
            }

            items[index].show();

            if (_.isFunction(callback)) {
                callback = _.wrap(callback, function(callback) {
                    items[curIndex].hide();
                    callback.call(this);
                });
            } else {
                callback = function() {
                    items[curIndex].hide();
                }
            }

            this.slide(type, callback);
        },
示例#9
0
文件: pool.js 项目: stesla/wsclient
 _.each(emitterMethods, function(m) {
   self[m] = _.wrap(socket[m], function(f, e) {
     var args = _.toArray(arguments).slice(1);
     if (_.include(["close", "open"], e)) { self.emitter[m].apply(self.emitter, args); }
     f.apply(socket, args);
   });
 });
示例#10
0
 sync: function(method, collection, options) {
     _.defaults(options || (options = {}), {
         xhrFields: {
             withCredentials: true
         },
         dataType: 'json',
         accepts: {
             json: 'application/hal+json'
         }
     });
     if (method === 'read') {
         var cached = this.getCached(options.cacheKey);
         if (cached) {
             var deferred = $.Deferred();
             if (options.success) {
                 deferred.done(options.success);
             }
             return deferred.resolve(cached).promise();
         } else {
             // Grab the response and cache
             options.success = options.success || function(collection, response, options) {};
             options.success = _.wrap(options.success, _.bind(function(success) {
                 this.setCached(options.cacheKey, arguments[1]);
                 success.apply(this, Array.prototype.slice.call(arguments, 1));
             }, this));
             this.promise = Backbone.Collection.prototype.sync.call(this, method, collection, options);
             return this.promise;
         }
     } else {
         this.promise = Backbone.Collection.prototype.sync.call(this, method, collection, options);
         return this.promise;
     }
 },
示例#11
0
		addSetter: function (item, options) {

			if (__.isFunction(options)) {
				options.func = options
			}
			options["overide"] = options["overide"] || false;

			// wrap setter function such that its value is passed in

			options.func = __.wrap(options.func, function(setter){
				setter(items[item].value);
			})

			if (!__.isUndefined(items[item]) && !__.isUndefined(items[item].set)) {

				if (!__.isUndefined(overide) && overide === true) {
					if (debug) console.log("Overiding setter for:", item);
					items[item].set = options.func;
					return true;
				} else {
					if (debug) console.warn("There is already a setter set for that item ["+item+"]: ", items[item].get);
			 		if (debug) console.info("Pass addSetter(item, func, overide) where Overide = true; to Overide.");
			 		return false;
				}		 	
			} else if (__.isUndefined(items[item])) {
				Hub.newItem(item, null, null, options.func);
				return true;
			} else {
				items[item].set = options.func;
				return true;
			}
		},
示例#12
0
var logify = function (obj, name) {
    if (typeof obj[name] !== 'function') return;
    var method = obj[name];
    obj[name] = _.wrap(method, function (method) {
        this.getLogger().debug('Function [%s]', name);
        return method.apply(this, _.rest(_.toArray(arguments)));
    });
};
示例#13
0
 ['beforeEach', 'afterEach', 'after', 'before', 'it'].forEach(function(method){      
   context[method] = _.wrap(context[method], function(fn){        
     var args = Array.prototype.slice.call(arguments, 1);
     if(_.isFunction(_.last(args))){
       args.push(fiberize(args.pop()));
     }
     fn.apply(this, args);
   });
 });
示例#14
0
 it("should wrap the first function inside of the wrapper function, passing it as the first argument", function() {
   var func = function() {
     return 2;
   };
   var result = _.wrap(func, function(func) {
     return 1 + func() + 3;
   });
   assert.strictEqual(result(), 6);
 });
示例#15
0
        setConfig: function(config) {
            var that = this;
            // configure AJAX object if it exists
            if (config.ajax !== undefined) {
                config.minimumInputLength = _.result(config, 'minimumInputLength', 0);
                config.initSelection = _.result(config, 'initSelection') || _.partial(initSelection, config);
                if (that.excluded) {
                    config.ajax.results = _.wrap(config.ajax.results, function(func, data, page) {
                        var response = func.call(this, data, page);
                        response.results = _.filter(response.results, function(item) {
                            return !item.hasOwnProperty('id') || _.indexOf(that.excluded, item.id) < 0;
                        });
                        return response;
                    });
                }
                config.ajax.quietMillis = _.result(config.ajax, 'quietMillis') || 700;
            } else {
                // configure non AJAX based Select2
                if (config.minimumResultsForSearch === undefined) {
                    config.minimumResultsForSearch = 7;
                }
                config.sortResults = function(results, container, query) {
                    if (!query.term || query.term.length < 1) {
                        return results;
                    }
                    var expression = tools.safeRegExp(query.term, 'im');

                    var sortIteratorDelegate = function(first, second) {
                        var inFirst = first.text.search(expression);
                        var inSecond = second.text.search(expression);

                        if (inFirst === -1 || inSecond === -1) {
                            return inSecond - inFirst;
                        }

                        return inFirst - inSecond;
                    };

                    return results.sort(sortIteratorDelegate);
                };
            }
            // set default values for other Select2 options
            if (config.formatResult === undefined) {
                config.formatResult = formatFabric(config, config.result_template || false);
            }
            if (config.formatSelection === undefined) {
                config.formatSelection = formatFabric(config, config.selection_template || false);
            }
            _.defaults(config, {
                escapeMarkup: function(m) { return m; },
                dropdownAutoWidth: true,
                openOnEnter: null
            });

            return config;
        },
示例#16
0
module.exports = function(ngin) {
  var SportsModel = ngin.SportsModel
  var config = ngin.config

  /**
   * FlightDefault Class
   *
   * @param {Object} attr
   * @param {Object} options
   * @api public
   */

  var FlightDefault = SportsModel.extend({

    urlRoot: function(options) {
      options = options || {}
      var tournamentID = options.tournament_id || this.tournament_id
      this.tournament_id = tournamentID
      delete options.tournament_id
      var base = config.urls && config.urls.sports || config.url
      return Url.resolve(base, 'tournaments/' + tournamentID + '/flight_defaults')
    },

    save: function(options, callback) {
      if (typeof options == 'function') {
        callback = options
        options = {}
      }

      options.method = options.method || 'PUT'
      FlightDefault.__super__.save.call(this, options, callback)
    },

    url: function(options){
      // Get base url
      var url = (this.urlRoot instanceof Function) ? this.urlRoot(options) : this.urlRoot
      // Add options as query parameters
      var separator = "?"
      _.each(options, function(val, key){
        url += separator + encodeURIComponent(key) + "=" + encodeURIComponent(val)
        separator = "&"
      })
      return url
    }

  })

  // wrap the inheirited list function with arg checking
  FlightDefault.list = _.wrap(FlightDefault.list, function(list, options, callback) {
    return callback(new Error('Not implemented'))
  })


  return FlightDefault

}
module.exports = function(ngin) {
  var SportsModel = ngin.SportsModel
  var config = ngin.config

  /**
   * StandingsPreference Class
   *
   * @param {Object} attr
   * @param {Object} options
   * @api public
   */

  var StandingsPreference = SportsModel.extend({

    urlRoot: function(options) {
      options = options || {}
      var subseasonID = options.subseason_id || this.subseason_id
      delete options.subseason_id

      var scope = ''
      if (options.pool_id || this.pool_id) {
        var poolID = options.pool_id || this.pool_id
        this.pool_id = poolID
        scope = '/pool/' + poolID
        delete options.pool_id
      } else if (options.division_id || this.division_id) {
        var divisionID = options.division_id || this.division_id
        this.division_id = divisionID
        scope = '/division/' + divisionID
        delete options.division_id
      }

      var base = config.urls && config.urls.sports || config.url
      return Url.resolve(base, 'subseasons/' + subseasonID + scope + '/standings_preference')
    },

    save: function(options, callback) {
      if (typeof options == 'function') {
        callback = options
        options = {}
      }
      options.method = options.method || 'PUT'
      StandingsPreference.__super__.save.call(this, options, callback)
    }

  })

  // wrap the inheirited list function with arg checking
  StandingsPreference.list = _.wrap(StandingsPreference.list, function(list, options, callback) {
    return callback(new Error('Not implemented'))
  })


  return StandingsPreference

}
示例#18
0
 initialize: function () {
     this.fetch = _.wrap(this.fetch.bind(this), function (fetch, options) {
         options || (options = {});
         options.data = _.defaults(options.data || {}, {
             imageSize: 'Sm',
             descriptionLang: 'en',
             api_key: config.tmsApiKey
         });
         fetch(options);
     });
 },
示例#19
0
        _.each(this.modules, function (value, key) {
            var path, module, region;
            (key.length > 0) ? path = this.path + "/" + key : path = this.path;
            path.substr(0, 1) == '/' ? path = path.substr(1) : path;

            if (typeof value === 'object') {
                region = window.Object.keys(value)[0];
                module = this.modules[key] = new value[region]({
                    path: path,
                    regionManager: this.region.regions[region]
                });
            } else {
                module = this.modules[key] = new value({path: path});
            }

            var before = _.wrap(module._handleBeforeRoute, function (method) {
                var args = Array.prototype.slice.call(arguments, 1),
                    scope = module;

                if (_this._handleBeforeRoute.apply(_this, args) === false) {
                    return false;
                }

                return method.apply(scope, args);

            });

            module._handleBeforeRoute = before;

            var after = _.wrap(module._handleAfterRoute, function (method) {
                var args = Array.prototype.slice.call(arguments, 1),
                    scope = module;

                _this._handleAfterRoute.apply(_this, args);
                method.apply(scope, args);

            })

            module._handleAfterRoute = after;

        }, this);
示例#20
0
        wrapRender: function () {
            var self = this;

            this.render = _.wrap(this.render, function(render) {
                var args = arguments;

                self.beforeRender.apply(self,args);
                render.apply(self,args);
                self.afterRender.apply(self,args);

                return self;
            });
        },
 _wrapMethod: function (method, model, options) {
   var key = this.policy.getKey(model, method, options);
   return _.wrap(options[options.targetMethod], _.bind(function (targetMethod, response) {
     if (targetMethod) {
       targetMethod(response);
     }
     if (options.generateKeyFromResponse) {
       key = this.policy.getKey(model, method, options);
     }
     if (options.responseHandler) {
       options.responseHandler(key, response, options);
     }
   }, this));
 },
示例#22
0
文件: pool.js 项目: stesla/wsclient
function Wrapper(socket) {
  var self = this;
  var emitterMethods = _.functions(events.EventEmitter.prototype);
  util.delegate(this, socket);
  self.emitter = new events.EventEmitter();
  _.each(emitterMethods, function(m) {
    self[m] = _.wrap(socket[m], function(f, e) {
      var args = _.toArray(arguments).slice(1);
      if (_.include(["close", "open"], e)) { self.emitter[m].apply(self.emitter, args); }
      f.apply(socket, args);
    });
  });
  self.close = _.wrap(socket.close, function(f) {
    _.each(self.emitter.listeners("close"), function(g) {
      socket.removeListener("close", g);
    });
    f.apply(socket, []);
    self.emitter.emit("close");
  });
  self.connect = _.wrap(socket.connect, function(f) {
    if (socket.isOpen()) { self.emitter.emit("open"); }
    f.apply(socket, []);
  });
};
示例#23
0
var augment = function(props) {
    var obj = this.prototype;
    for (var key in props) {
        if (typeof props[key] === 'function') {
            obj[key] = _.wrap(obj[key], props[key]);
        } else if (_.isArray(props[key])) {
            obj[key] = _.isArray(obj[key]) ? obj[key].concat(props[key]) : props[key];
        } else if (typeof props[key] === 'object') {
            obj[key] = _.extend({}, obj[key], props[key]);
        } else {
            obj[key] = props[key];
        }
    }

    return this;
};
示例#24
0
文件: index.js 项目: lizzz0523/Zoe
        slide : function(type, callback) {
            var $slider = this.$view,

                vertical = this.vertical,

                init = {},
                dest = {};

            switch (type) {
                case ZSlider.TYPE_PREV :
                    if (vertical) {
                        init.top = '-100%';
                        dest.top = '0';
                    } else {
                        init.left = '-100%';
                        dest.left = '0';
                    }

                    break;

                case ZSlider.TYPE_NEXT :
                    if (vertical) {
                        init.top = '0';
                        dest.top = '-100%';
                    } else {
                        init.left = '0';
                        dest.left = '-100%';
                    }

                    break;
            }

            if (_.isFunction(callback)) {
                callback = _.wrap(callback, function(callback) {
                    $slider.css({left : 0, top : 0});
                    callback.call(this);
                });
            } else {
                callback = function() {
                    $slider.css({left : 0, top : 0});
                }
            }

            $slider.css(init).animate(dest, this.speed, _.bind(callback, this));
        },
示例#25
0
		addGetter: function (item, options) {

			if (__.isFunction(options)) {
				options.func = options
			}
			options["requires"] = options["requires"] || [];
			options["overide"] = options["overide"] || false;

			// wrap getter function such that its requires are all passed in

			options.func = __.wrap(options.func, function(getter){
				var requires = {};
				__.each(options.requires, function(it){
					requires[it] = items[it].value;
				})
				getter(requires);
			})

			if (__.isUndefined(options.func)) {
				if (debug) console.log("No getter passed in options ie: addGetter('item', { func: function() { .... }})")
				return false;
			} 

			if (!__.isUndefined(items[item]) && !__.isUndefined(items[item].get)) {

				if (!__.isUndefined(options.overide) && options.overide === true) {
					if (debug) console.log("Overiding getter for:", item);
					items[item].get = options.func;
					Hub.addRequirements(item, options.requires)
					return true;
				} else {
					if (debug) console.warn("There is already a getter set for that item ["+item+"]: ", items[item].get);
			 		if (debug) console.info("Pass addGetter(item, func, overide) where Overide = true; to Overide.");
			 		return false;
				}		 	
			} else if (__.isUndefined(items[item])) {
				Hub.newItem(item, null, options.func);
				Hub.addRequirements(item, options.requires)
				return true;
			} else {
				items[item].get = options.func;
				Hub.addRequirements(item, options.requires)
				return true;
			}
		},
示例#26
0
		_.each(this.events, function (method, eventName) {
			// wrap the event in an authentication filter:
			var authFiltered = _.wrap(method, function (meth) {
				var method_args = arguments;

				if ((client.get("authenticated") === false) && 
					!_.contains(server.unauthenticatedEvents, eventName)) {
					return;
				}
				//DEBUG && console.log(eventName + ":" + namespace);
				method_args = Array.prototype.slice.call(method_args).splice(1); // first argument is the function itself
				method_args.unshift(namespace, socket, channel, client);
				meth.apply(server, method_args); // not even once.
			});

			// bind the pre-filtered event
			socket.on(eventName + ":" + namespace, authFiltered);
		});
示例#27
0
    constructor: function (options) {
        _.bindAll(this, 'render', 'beforeRender', 'afterRender');
        var _this = this,
            render = this.render,
            before = this.beforeRender,
            after = this.afterRender;

        options || (options = {});
        _.extend(this, _.pick(options, ['channelName']));
        this.channelName || (this.channelName = _.uniqueId('channel'));

        this.render = _.wrap(render, function () {
            before();
            render.call(_this);
            after();
        });
        Backbone.View.apply(this, arguments);
    },
示例#28
0
 ['beforeEach', 'afterEach', 'after', 'before', 'it'].forEach(function(method){
   var original = context[method];
   context[method] = _.wrap(original, function(fn){
     var args = Array.prototype.slice.call(arguments, 1);
     if(_.isFunction(_.last(args))){
       args.push(fiberize(args.pop()));
     }
     return fn.apply(this, args);
   });
   _.extend(context[method], _(original).pick('only', 'skip'));
   if (context[method].only) {
     context[method].only = function(only) {
       return function(title, fn) {
         return only(title, fiberize(fn));
       }
     }(context[method].only);
   }
 });
示例#29
0
duality_events.on('init', function () {

    try {
        app_settings = appinfo.getAppInfo.call(this);
    } catch(e) {
        shows.render500('Failed to retrieve settings.');
        console.error('Failed to retrieve settings.');
        throw e;
    }

    // render top nav labels
    $('#topnav .nav .activity a').append(' ' + $.kansotranslate('Activity'));
    $('#topnav .nav .sms-forms-data a').append(' ' + $.kansotranslate('Export'));
    $('#topnav .nav .facilities a').append(' ' + $.kansotranslate('Facilities'));

    // Set version on all pages
    $('.version').text(settings.version);

    // Dynamic year for footer copyright
    $("#year").text(new Date().getFullYear());

    // patch dropdown to fire an event
    $.fn.dropdown.Constructor.prototype.toggle = _.wrap($.fn.dropdown.Constructor.prototype.toggle, function(fn, e) {
        fn.call(this, e);
        $(this).trigger('toggle');
    });

    // hack to bind to dynamic elements. Executes far too often. We can do better.
    $(document).on('mouseenter', initBootstrap);

    // add handler to docsPageLoader event for #supportedforms + p elements
    $(document).on('docsPageLoaded', wrapCodeBlocks);

    // our version of bootstrap does not clear error on textareas
    $(document).on('focus', 'textarea', function(ev) {
        $(ev.target).closest('.control-group').removeClass('error');
    });

    $(document).on('click', '.controls .edit-mode .btn', data_records.handleUpdateDropdown);
    $(document).on('click', '.add-message button, .add-message a', data_records.handleSendMessage);

    data_records.onDualityInit();

});
示例#30
0
 fetch: function(options) {
     if (options && options.success) {
         options.success = _.wrap(options.success, _.bind(function(success) {
             // We've successfully queried the API for something that
             // requires authentication but we're in an unauthenticated
             // state.  Double-check our authentication and proceed.
             var args = Array.prototype.slice.call(arguments, 1);
             if (this.requiresAuth && !this.auth.isAuthenticated()) {
                 this.auth.fetchUser()
                 .always(function() {
                     success.apply(this, args);
                 });
             } else {
                 success.apply(this, args);
             }
         }, this));
         // TODO - maybe wrap error to handle 401?
     }
     return Backbone.Collection.prototype.fetch.call(this, options);
 },