示例#1
0
function Selectable(selector, el) {
  if (!(this instanceof Selectable)) return new Selectable(selector, el);
  this.el = el || document.documentElement;
  this.selector = selector;
  this.events = events(this.el, this);
  this.rect = new SelectionRect;
  this.events.bind('mousedown');
  this.events.bind('mousemove');
  this.events.bind('mouseup');
}

/**
 * Mixin emitter.
 */

Emitter(Selectable.prototype);

/**
 * Handle mousedown.
 */

Selectable.prototype.onmousedown = function(e){
  this.down = e;
  this.el.appendChild(this.rect.el);
  this.rect.moveTo(e.pageX, e.pageY);
};

/**
 * Handle mousemove.
 */
示例#2
0
 */

function Request(opts) {
  var self = this;

  // figure out if request needs to be xdomain
  self.method = opts.method || 'GET';
  self.uri = opts.uri;
  self.xd = !!opts.xd || isXD(self.uri);
  self.async = false !== opts.async;
  self.withCredentials = !!opts.withCredentials;
  self.data = undefined != opts.data ? opts.data : null;
  self.create();
}

Emitter(Request.prototype);

/**
 * Creates the XHR object and sends the request.
 *
 * @api private
 */

Request.prototype.create = function() {
  var self = this;
  var xhr = create(self.xd);

  xhr.open(self.method, self.uri, self.async);

  if ('POST' == self.method) {
    try {
示例#3
0
module.exports = function (options) {

    var em = emitter({}),

        socket = options.socket,

        /**
         * Wraps function with setTimeout
         */
        async = function (fn) {
            return function () {
                var args = arguments;
                return setTimeout(function () {
                    fn.apply(null, args);
                }, 0);
            }
        },

        /**
         * Unsubscribe an from Object / Query
         *
         * @param _id object or query id
         * @param fn event handler
         */
        unsubscribe = async(function (_id, fn) {
            if (typeof _id === 'undefined') { throw new Error('_id is not defined'); }
            if (fn) { em.off(_id, fn); }

            socket.emit('unsub', _id);
        }),

        /**
         * Wraps callback function
         *
         * @param _id object or query id
         * @param fn callback
         * @return function
         */
        createCallback = function (_id, fn) {
            return function (notification) {

                _id = _id;
                if (notification.doc) {
                    _id = notification.doc._id;
                }

                var handler,
                    isSubscribed = true,
                    unsub = _.once(function () {
                        isSubscribed = false;
                        unsubscribe(_id, handleNotification);
                    }),

                    handleNotification = function (notification) {
                        if (isSubscribed) {
                            if (typeof handler === 'function') {
                                handler(notification);
                            } else {
                                var fn = handler[notification.event];
                                if (fn) {
                                    fn(notification);
                                }
                            }
                        }
                    };

                if (fn) {
                    handler = fn(notification, unsub);
                    if (handler && notification.event !== 'error') {
                        em.on(_id, handleNotification);
                    }
                }
                if (!handler) {
                    unsub();
                }
            };
        },

        api = map({

            /**
             * Get an object
             *
             * @param _id
             * @param fn
             */
            get: function (_id, fn) {
                socket.emit('get', _id, createCallback(_id, fn));
            },

            /**
             * Update / Insert an object
             *
             * @param obj
             * @param fn
             */
            put: function (obj, fn) {
                socket.emit('put', obj, createCallback(obj._id, fn));
            },

            /**
             * Delete an object
             *
             * @param _id
             * @param fn
             */
            del: function (_id, fn) {
                socket.emit('del', _id, fn);
            },

            /**
             * Query
             *
             * @param query MongoDB query object
             * @param callback
             */
            query: function (query, callback) {
                socket.emit('query', query, createCallback(getQueryId(query), callback));
            }

        }, async);

    socket.on('notify', function (_id, notification) {
        em.emit(_id, notification);
    });

    return api;
};
  this.on('change', bind(this, this.show));
  this.days.on('prev', bind(this, this.prev));
  this.days.on('next', bind(this, this.next));
  this.days.on('year', bind(this, this.menuChange, 'year'));
  this.days.on('month', bind(this, this.menuChange, 'month'));
  this.show(date || new Date);
  this.days.on('change', function(date){
    self.emit('change', date);
  });
}

/**
 * Mixin emitter.
 */

Emitter(Calendar.prototype);

/**
 * Add class `name` to differentiate this
 * specific calendar for styling purposes,
 * for example `calendar.addClass('date-picker')`.
 *
 * @param {String} name
 * @return {Calendar}
 * @api public
 */

Calendar.prototype.addClass = function(name){
  classes(this.el).add(name);
  return this;
};
示例#5
0
文件: index.js 项目: Retsly/swipe
  this.current = 0;
  this.el = el;
  this.refresh();
  this.interval(5000);
  this.duration(300);
  this.fastThreshold(200);
  this.threshold(0.5);
  this.show(0, 0, { silent: true });
  this.bind();
}

/**
 * Mixin `Emitter`.
 */

Emitter(Swipe.prototype);

/**
 * Set the swipe threshold to `n`.
 *
 * This is the factor required for swipe
 * to detect when a slide has passed the
 * given threshold, and may display the next
 * or previous slide. For example the default
 * of `.5` means that the user must swipe _beyond_
 * half of the side width.
 *
 * @param {Number} n
 * @api public
 */
示例#6
0
文件: view.js 项目: 3manuek/app
function ProfileView() {
  if (!(this instanceof ProfileView)) {
    return new ProfileView();
  };

  this.el = render.dom(profile);

  this.events = events(this.el, this);
  this.switchOn();
}

/**
 * Mixin with `Emitter`
 */

Emitter(ProfileView.prototype);


/**
 * Turn on event bindings
 */

ProfileView.prototype.switchOn = function() {
  this.events.bind('submit form');
  this.on('submit', this.formsubmit.bind(this));
  this.on('success', this.onsuccess.bind(this));
  this.on('error', this.onerror.bind(this));
}

/**
 * Turn off event bindings
示例#7
0
var Emitter = require('emitter');

/**
 * Expose Editable
 */
exports = module.exports = Editable;

/**
 * Editable
 */
function Editable(el, title) {
    if (!(this instanceof Editable)) return new Editable(el, title);
    this.init(el, title);
}

Emitter(Editable.prototype);

Editable.prototype.init = function (el, title) {
    var that = this;

    that.el = el;
    that.title = title || 'Click to edit.';
    that.content = that.el.innerHTML;

    that.el.setAttribute('contentEditable', true);
    that.el.setAttribute('title', that.title);

    // W3C
    if (that.el.addEventListener) {
        that.el.addEventListener('keydown', function () {
            that.onKeydown(event);
示例#8
0
文件: index.js 项目: kelonye/dex
  this.onerror = this.emit.bind(this, 'error');
  this.oncomplete = this.oncomplete.bind(this);
  this.onconnect = this.onconnect.bind(this);
  this.onabort = this.onabort.bind(this);
  this.batch = new Batch;
  this.delegate();
  this.transactions = {};
  this.queue = [];
  this.connect();
}

/**
 * Mixins
 */

Emitter(Database.prototype);

/**
 * Define a command.
 *
 * @param {String} name
 * @param {Function} fn
 * @return {Database}
 * @api public
 */

Database.command = command;

/**
 * Connect.
 *
示例#9
0
文件: move.js 项目: skishore/translit
 (function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module._resolving&&!module.exports){var mod={};mod.exports={};mod.client=mod.component=true;module._resolving=true;module.call(this,mod.exports,require.relative(resolved),mod);delete module._resolving;module.exports=mod.exports}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("/")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("/"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("/")+"/deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("component-transform-property/index.js",function(exports,require,module){var styles=["webkitTransform","MozTransform","msTransform","OTransform","transform"];var el=document.createElement("p");var style;for(var i=0;i<styles.length;i++){style=styles[i];if(null!=el.style[style]){module.exports=style;break}}});require.register("component-has-translate3d/index.js",function(exports,require,module){var prop=require("transform-property");if(!prop||!window.getComputedStyle)return module.exports=false;var map={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};var el=document.createElement("div");el.style[prop]="translate3d(1px,1px,1px)";document.body.insertBefore(el,null);var val=getComputedStyle(el).getPropertyValue(map[prop]);document.body.removeChild(el);module.exports=null!=val&&val.length&&"none"!=val});require.register("yields-has-transitions/index.js",function(exports,require,module){exports=module.exports=function(el){switch(arguments.length){case 0:return bool;case 1:return bool?transitions(el):bool}};function transitions(el,styl){if(el.transition)return true;styl=window.getComputedStyle(el);return!!parseFloat(styl.transitionDuration,10)}var styl=document.body.style;var bool="transition"in styl||"webkitTransition"in styl||"MozTransition"in styl||"msTransition"in styl});require.register("component-event/index.js",function(exports,require,module){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}});require.register("ecarter-css-emitter/index.js",function(exports,require,module){var events=require("event");var watch=["transitionend","webkitTransitionEnd","oTransitionEnd","MSTransitionEnd","animationend","webkitAnimationEnd","oAnimationEnd","MSAnimationEnd"];module.exports=CssEmitter;function CssEmitter(element){if(!(this instanceof CssEmitter))return new CssEmitter(element);this.el=element}CssEmitter.prototype.bind=function(fn){for(var i=0;i<watch.length;i++){events.bind(this.el,watch[i],fn)}};CssEmitter.prototype.unbind=function(fn){for(var i=0;i<watch.length;i++){events.unbind(this.el,watch[i],fn)}}});require.register("component-once/index.js",function(exports,require,module){var n=0;var global=function(){return this}();module.exports=function(fn){var id=n++;var called;function once(){if(this==global){if(called)return;called=true;return fn.apply(this,arguments)}var key="__called_"+id+"__";if(this[key])return;this[key]=true;return fn.apply(this,arguments)}return once}});require.register("yields-after-transition/index.js",function(exports,require,module){var has=require("has-transitions"),emitter=require("css-emitter"),once=require("once");var supported=has();module.exports=after;function after(el,fn){if(!supported||!has(el))return fn();emitter(el).bind(fn);return fn}after.once=function(el,fn){var callback=once(fn);after(el,fn=function(){emitter(el).unbind(fn);callback()})}});require.register("component-indexof/index.js",function(exports,require,module){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}});require.register("component-emitter/index.js",function(exports,require,module){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}});require.register("yields-css-ease/index.js",function(exports,require,module){module.exports={"in":"ease-in",out:"ease-out","in-out":"ease-in-out",snap:"cubic-bezier(0,1,.5,1)",linear:"cubic-bezier(0.250, 0.250, 0.750, 0.750)","ease-in-quad":"cubic-bezier(0.550, 0.085, 0.680, 0.530)","ease-in-cubic":"cubic-bezier(0.550, 0.055, 0.675, 0.190)","ease-in-quart":"cubic-bezier(0.895, 0.030, 0.685, 0.220)","ease-in-quint":"cubic-bezier(0.755, 0.050, 0.855, 0.060)","ease-in-sine":"cubic-bezier(0.470, 0.000, 0.745, 0.715)","ease-in-expo":"cubic-bezier(0.950, 0.050, 0.795, 0.035)","ease-in-circ":"cubic-bezier(0.600, 0.040, 0.980, 0.335)","ease-in-back":"cubic-bezier(0.600, -0.280, 0.735, 0.045)","ease-out-quad":"cubic-bezier(0.250, 0.460, 0.450, 0.940)","ease-out-cubic":"cubic-bezier(0.215, 0.610, 0.355, 1.000)","ease-out-quart":"cubic-bezier(0.165, 0.840, 0.440, 1.000)","ease-out-quint":"cubic-bezier(0.230, 1.000, 0.320, 1.000)","ease-out-sine":"cubic-bezier(0.390, 0.575, 0.565, 1.000)","ease-out-expo":"cubic-bezier(0.190, 1.000, 0.220, 1.000)","ease-out-circ":"cubic-bezier(0.075, 0.820, 0.165, 1.000)","ease-out-back":"cubic-bezier(0.175, 0.885, 0.320, 1.275)","ease-out-quad":"cubic-bezier(0.455, 0.030, 0.515, 0.955)","ease-out-cubic":"cubic-bezier(0.645, 0.045, 0.355, 1.000)","ease-in-out-quart":"cubic-bezier(0.770, 0.000, 0.175, 1.000)","ease-in-out-quint":"cubic-bezier(0.860, 0.000, 0.070, 1.000)","ease-in-out-sine":"cubic-bezier(0.445, 0.050, 0.550, 0.950)","ease-in-out-expo":"cubic-bezier(1.000, 0.000, 0.000, 1.000)","ease-in-out-circ":"cubic-bezier(0.785, 0.135, 0.150, 0.860)","ease-in-out-back":"cubic-bezier(0.680, -0.550, 0.265, 1.550)"}});require.register("component-query/index.js",function(exports,require,module){function one(selector,el){return el.querySelector(selector)}exports=module.exports=function(selector,el){el=el||document;return one(selector,el)};exports.all=function(selector,el){el=el||document;return el.querySelectorAll(selector)};exports.engine=function(obj){if(!obj.one)throw new Error(".one callback required");if(!obj.all)throw new Error(".all callback required");one=obj.one;exports.all=obj.all;return exports}});require.register("move/index.js",function(exports,require,module){var after=require("after-transition");var has3d=require("has-translate3d");var Emitter=require("emitter");var ease=require("css-ease");var query=require("query");var translate=has3d?["translate3d(",", 0)"]:["translate(",")"];module.exports=Move;var style=window.getComputedStyle||window.currentStyle;Move.version="0.3.2";Move.ease=ease;Move.defaults={duration:500};Move.select=function(selector){if("string"!=typeof selector)return selector;return query(selector)};function Move(el){if(!(this instanceof Move))return new Move(el);if("string"==typeof el)el=query(el);if(!el)throw new TypeError("Move must be initialized with element or selector");this.el=el;this._props={};this._rotate=0;this._transitionProps=[];this._transforms=[];this.duration(Move.defaults.duration)}Emitter(Move.prototype);Move.prototype.transform=function(transform){this._transforms.push(transform);return this};Move.prototype.skew=function(x,y){return this.transform("skew("+x+"deg, "+(y||0)+"deg)")};Move.prototype.skewX=function(n){return this.transform("skewX("+n+"deg)")};Move.prototype.skewY=function(n){return this.transform("skewY("+n+"deg)")};Move.prototype.translate=Move.prototype.to=function(x,y){return this.transform(translate.join(""+x+"px, "+(y||0)+"px"))};Move.prototype.translateX=Move.prototype.x=function(n){return this.transform("translateX("+n+"px)")};Move.prototype.translateY=Move.prototype.y=function(n){return this.transform("translateY("+n+"px)")};Move.prototype.scale=function(x,y){return this.transform("scale("+x+", "+(y||x)+")")};Move.prototype.scaleX=function(n){return this.transform("scaleX("+n+")")};Move.prototype.scaleY=function(n){return this.transform("scaleY("+n+")")};Move.prototype.rotate=function(n){return this.transform("rotate("+n+"deg)")};Move.prototype.ease=function(fn){fn=ease[fn]||fn||"ease";return this.setVendorProperty("transition-timing-function",fn)};Move.prototype.animate=function(name,props){for(var i in props){if(props.hasOwnProperty(i)){this.setVendorProperty("animation-"+i,props[i])}}return this.setVendorProperty("animation-name",name)};Move.prototype.duration=function(n){n=this._duration="string"==typeof n?parseFloat(n)*1e3:n;return this.setVendorProperty("transition-duration",n+"ms")};Move.prototype.delay=function(n){n="string"==typeof n?parseFloat(n)*1e3:n;return this.setVendorProperty("transition-delay",n+"ms")};Move.prototype.setProperty=function(prop,val){this._props[prop]=val;return this};Move.prototype.setVendorProperty=function(prop,val){this.setProperty("-webkit-"+prop,val);this.setProperty("-moz-"+prop,val);this.setProperty("-ms-"+prop,val);this.setProperty("-o-"+prop,val);return this};Move.prototype.set=function(prop,val){this.transition(prop);this._props[prop]=val;return this};Move.prototype.add=function(prop,val){if(!style)return;var self=this;return this.on("start",function(){var curr=parseInt(self.current(prop),10);self.set(prop,curr+val+"px")})};Move.prototype.sub=function(prop,val){if(!style)return;var self=this;return this.on("start",function(){var curr=parseInt(self.current(prop),10);self.set(prop,curr-val+"px")})};Move.prototype.current=function(prop){return style(this.el).getPropertyValue(prop)};Move.prototype.transition=function(prop){if(!this._transitionProps.indexOf(prop))return this;this._transitionProps.push(prop);return this};Move.prototype.applyProperties=function(){for(var prop in this._props){this.el.style.setProperty(prop,this._props[prop])}return this};Move.prototype.move=Move.prototype.select=function(selector){this.el=Move.select(selector);return this};Move.prototype.then=function(fn){if(fn instanceof Move){this.on("end",function(){fn.end()})}else if("function"==typeof fn){this.on("end",fn)}else{var clone=new Move(this.el);clone._transforms=this._transforms.slice(0);this.then(clone);clone.parent=this;return clone}return this};Move.prototype.pop=function(){return this.parent};Move.prototype.reset=function(){this.el.style.webkitTransitionDuration=this.el.style.mozTransitionDuration=this.el.style.msTransitionDuration=this.el.style.oTransitionDuration=0;return this};Move.prototype.end=function(fn){var self=this;this.emit("start");if(this._transforms.length){this.setVendorProperty("transform",this._transforms.join(" "))}this.setVendorProperty("transition-properties",this._transitionProps.join(", "));this.applyProperties();if(fn)this.then(fn);after.once(this.el,function(){self.reset();self.emit("end")});return this}});require.alias("component-has-translate3d/index.js","move/deps/has-translate3d/index.js");require.alias("component-has-translate3d/index.js","has-translate3d/index.js");require.alias("component-transform-property/index.js","component-has-translate3d/deps/transform-property/index.js");require.alias("yields-after-transition/index.js","move/deps/after-transition/index.js");require.alias("yields-after-transition/index.js","move/deps/after-transition/index.js");require.alias("yields-after-transition/index.js","after-transition/index.js");require.alias("yields-has-transitions/index.js","yields-after-transition/deps/has-transitions/index.js");require.alias("yields-has-transitions/index.js","yields-after-transition/deps/has-transitions/index.js");require.alias("yields-has-transitions/index.js","yields-has-transitions/index.js");require.alias("ecarter-css-emitter/index.js","yields-after-transition/deps/css-emitter/index.js");require.alias("component-emitter/index.js","ecarter-css-emitter/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("component-event/index.js","ecarter-css-emitter/deps/event/index.js");require.alias("component-once/index.js","yields-after-transition/deps/once/index.js");require.alias("yields-after-transition/index.js","yields-after-transition/index.js");require.alias("component-emitter/index.js","move/deps/emitter/index.js");require.alias("component-emitter/index.js","emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("yields-css-ease/index.js","move/deps/css-ease/index.js");require.alias("yields-css-ease/index.js","move/deps/css-ease/index.js");require.alias("yields-css-ease/index.js","css-ease/index.js");require.alias("yields-css-ease/index.js","yields-css-ease/index.js");require.alias("component-query/index.js","move/deps/query/index.js");require.alias("component-query/index.js","query/index.js");if(typeof exports=="object"){module.exports=require("move")}else if(typeof define=="function"&&define.amd){define(function(){return require("move")})}else{this["move"]=require("move")}})();
示例#10
0
 * @param {Element} el
 */

function Sortable(el){
  if (!(this instanceof Sortable)) return new Sortable(el);
  if (!el) throw new TypeError('sortable(): expects an element');
  this.events = events(el, this);
  this.els = el.children;
  this.el = el;
}

/**
 * Mixins.
 */

emitter(Sortable.prototype);

/**
 * Ignore items that don't match `selector`.
 *
 * @param {String} selector
 * @return {Sortable}
 * @api public
 */

Sortable.prototype.ignore = function(selector){
  this.ignored = selector;
  return this;
};

/**
示例#11
0
function EditorControls( camera, domElement ) {

  if ( !(this instanceof EditorControls) ) { return new EditorControls( camera, domElement ); }
  this.domElement = ( domElement !== undefined ) ? domElement : document;

  // API
  Emitter( this );

  this.enabled = false;
  this.sketching = false;

  var handlers = {
    contextmenu: onContextMenu,
    mousedown: onMouseDown,
    mousewheel: onMouseWheel,
    DOMMouseScroll: onMouseWheel,
    touchstart: touchStart,
    touchmove: touchMove,
    touchend: touchEnd
  };

  function makeFilter( filter ) {
    var fn = function() { return true; };
    if ( typeof filter === 'string' ) {
      fn = function( x ) { return x === filter; };
    } else if ( Array.isArray( filter ) ) {
      fn = function( x ) { return filter.indexOf( x ) !== -1; };
    } else if ( typeof filter  === 'function' ) {
      fn = filter;
    }
    return fn;
  }

  this.enable = function( filter ) {
    if ( this.domElement && !this.enabled ) {
      this.listenTo( this.domElement, makeFilter( filter ) );
      this.enabled = true;
    }
  };

  this.disable = function( filter ) {
    this.stopListening( makeFilter( filter ) );
    this.enabled = false;
  };

  this.listenTo = function( domElement, filter ) {
    this.domElement = domElement;
    filter || ( filter = function() { return true; } );
    Object
      .keys( handlers )
      .filter( filter )
      .forEach( function( k ) {
        domElement.addEventListener( k, handlers[ k ], false );
      } );
  };

  this.stopListening = function( filter ) {
    if ( this.domElement ) {
      var el = this.domElement;
      filter || ( filter = function() { return true; } );
      Object
        .keys( handlers )
        .filter( filter )
        .forEach( function( k ) {
          el.removeEventListener( k, handlers[ k ] );
        } );
    }
  };

  var currentStroke = [];
  var currentStrokeId = -1;

  function onContextMenu( event ) { event.preventDefault(); }

  // internals

  var scope = this;
  var vector = new THREE.Vector3();

  var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, SKETCH: 3 };
  scope.rotateEnabled = true;

  var HOLD = false;
  var setHoldTimeOutId = null;

  var state = STATE.NONE;

  var center = new THREE.Vector3();
  var normalMatrix = new THREE.Matrix3();

  // events

  var changeEvent = { type: 'change' };

  this.focus = function ( target ) {

	  center.getPositionFromMatrix( target.matrixWorld );
	  camera.lookAt( center );

	  scope.dispatchEvent( changeEvent );

  };

  this.getCenter = function() { return center.clone(); };
  this.setCenter = function( x, y, z ) {
    if ( x instanceof THREE.Vector3 ) {
      center = x.clone();
    } else {
      center = new THREE.Vector3( x || 0, y || 0, z || 0 );
    }
  };

  this.getCamera = function() { return camera; };
  this.setCamera = function( c ) { camera = c; };

  this.pan = function ( distance ) {

	  normalMatrix.getNormalMatrix( camera.matrix );

	  distance.applyMatrix3( normalMatrix );
	  distance.multiplyScalar( vector.copy( center ).sub( camera.position ).length() * 0.001 );

	  camera.position.add( distance );
	  center.add( distance );

	  scope.dispatchEvent( changeEvent );

  };

  this.zoom = function ( distance ) {

	  normalMatrix.getNormalMatrix( camera.matrix );

	  distance.applyMatrix3( normalMatrix );
	  distance.multiplyScalar( vector.copy( center ).sub( camera.position ).length() * 0.001 );

	  camera.position.add( distance );

	  scope.dispatchEvent( changeEvent );

  };

  this.rotate = function ( delta ) {

	  vector.copy( camera.position ).sub( center );

	  // var theta = Math.atan2( vector.y, vector.x );
	  // var phi = Math.atan2( Math.sqrt( vector.x * vector.x + vector.y * vector.y ), vector.z );


	  var theta = Math.atan2( vector.x, vector.z );
	  var phi = Math.atan2( Math.sqrt( vector.x * vector.x + vector.z * vector.z ), vector.y );

	  theta += delta.x;
	  phi += delta.y;

	  var EPS = 0.000001;

	  phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

	  var radius = vector.length();

	  vector.x = radius * Math.sin( phi ) * Math.sin( theta );
	  vector.y = radius * Math.cos( phi );
	  vector.z = radius * Math.sin( phi ) * Math.cos( theta );

	  // vector.y = radius * Math.sin( phi ) * Math.sin( theta );
	  // vector.z = radius * Math.cos( phi );
	  // vector.x = radius * Math.sin( phi ) * Math.cos( theta );

	  camera.position.copy( center ).add( vector );

	  camera.lookAt( center );

	  scope.dispatchEvent( changeEvent );

  };

  // mouse

  function onMouseDown( event ) {

	  // if ( scope.enabled === false ) return;

	  event.preventDefault();

    // left button to sketch
	  if ( event.button === 0 ) {

	    state = STATE.ROTATE;
	    // state = STATE.SKETCH;

	  } else if ( event.button === 1 ) {

	    state = STATE.ZOOM;
	    // state = STATE.PAN;

	  } else if ( event.button === 2 ) {

	    state = STATE.PAN;
	    // state = STATE.ROTATE;

	  }

	  scope.domElement.addEventListener( 'mousemove', onMouseMove, false );
	  scope.domElement.addEventListener( 'mouseup', onMouseUp, false );
	  scope.domElement.addEventListener( 'mouseout', onMouseUp, false );

    if ( scope.sketching ) {
      scope.emit( 'sketchStart', { x: event.clientX, y: event.clientY } );
    }
    // currentStrokeId = strokeRenderer.add( currentStroke );
  }

  function onMouseMove( event ) {

	  // if ( scope.enabled === false ) return;

	  event.preventDefault();

    if ( scope.sketching ) {
      mouseSketching( event );
      return;
    }

	  var movementX = event.movementX || event.webkitMovementX || event.mozMovementX || event.oMovementX || 0;
	  var movementY = event.movementY || event.webkitMovementY || event.mozMovementY || event.oMovementY || 0;

	  if ( state === STATE.ROTATE && scope.rotateEnabled ) {

	    scope.rotate( new THREE.Vector3( - movementX * 0.005, - movementY * 0.005, 0 ) );

	  } else if ( state === STATE.ZOOM ) {

	    scope.zoom( new THREE.Vector3( 0, 0, movementY ) );

	  } else if ( state === STATE.PAN ) {

	    scope.pan( new THREE.Vector3( - movementX, movementY, 0 ) );

	  }

    // else if ( state === STATE.SKETCH ) {

      // mouseSketching( event );

    // }

  }

  function getOffsetToWindow( el ) {
    var x = el.offsetLeft, y = el.offsetTop;

    el = el.offsetParent;

    while ( el )  {
      x += el.offsetLeft;
      y += el.offsetTop;
      el = el.offsetParent;
    }
    return {
      left: x,
      top: y
    };
  }

  var mouseSketching = function() {
    var offset = getOffsetToWindow( domElement );
    var left = offset.left, top = offset.top;
    return function( event ) {
      var p = { x: event.clientX - left, y: event.clientY - top };
      currentStroke.push( p );
      scope.emit( 'sketching', p );
    };
  }();

  var touchSketching = function() {
    var offset = getOffsetToWindow( domElement );
    var left = offset.left, top = offset.top;
    return function( event ) {
      var t = event.touches[ 0 ];
      if ( t ) {
        var p = { x: t.clientX - left, y: t.clientY - top };
        currentStroke.push( p );
        scope.emit( 'sketching', p );
      }
    };
  }();

  function oneStroke() {
    // strokeRenderer.clear();
    scope.emit( 'oneStroke', currentStroke );
    currentStroke = [];
  }

  function onMouseUp( event ) {

	  // if ( scope.enabled === false ) return;

	  scope.domElement.removeEventListener( 'mousemove', onMouseMove, false );
	  scope.domElement.removeEventListener( 'mouseup', onMouseUp, false );
	  scope.domElement.removeEventListener( 'mouseout', onMouseUp, false );

	  state = STATE.NONE;

    if ( scope.sketching ) {
      oneStroke();
    }
  }

  function onMouseWheel( event ) {

	  // if ( scope.enabled === false ) return;

    if ( state === STATE.PAN ) {
      return;
    }

	  var delta = 0;

	  if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

	    delta = - event.wheelDelta;

	  } else if ( event.detail ) { // Firefox

	    delta = event.detail * 10;

	  }

	  scope.zoom( new THREE.Vector3( 0, 0, delta ) );

  }

  // // touch

  // var touch = new THREE.Vector3();
  // var prevTouch = new THREE.Vector3();
  // var prevDistance = null;
  // var zoomSpeed = 4;
  // var rotateOrZoomThreshold = 25;

  // function touchStart( event ) {

	//   // if ( scope.enabled === false ) return;

	//   var touches = event.touches;

	//   switch ( touches.length ) {


	//   case 1:
	//     prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
  //     scope.emit( 'sketchStart', { x: touches[ 0 ].pageX, y: touches[ 0 ].pageY } );
	//     break;

  //   case 2:
	//     var dx = touches[ 0 ].pageX - touches[ 1 ].pageX;
	//     var dy = touches[ 0 ].pageY - touches[ 1 ].pageY;
  //     var cx = 0.5 * ( touches[ 0 ].pageX + touches[ 1 ].pageX );
	//     var cy = 0.5 * ( touches[ 0 ].pageY + touches[ 1 ].pageY );
	//     prevDistance = Math.sqrt( dx * dx + dy * dy ) * zoomSpeed;
	//     prevTouch.set( cx, cy, 0 );
	//     break;

  //   default:
	//     prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
  //     break;
	//   }

  // }

  // function touchMove( event ) {

	//   // if ( scope.enabled === false ) return;

	//   event.preventDefault();
	//   event.stopPropagation();

	//   var touches = event.touches;


	//   switch ( touches.length ) {

	//   case 1:
	//     touch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
  //     touchSketching( event );
	//     prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
	//     break;

	//   case 2:
  //     var cx = 0.5 * ( touches[ 0 ].pageX + touches[ 1 ].pageX );
	//     var cy = 0.5 * ( touches[ 0 ].pageY + touches[ 1 ].pageY );
	//     touch.set( cx, cy, 0 );

  //     // figure out rotate or zoom:
  //     if ( touch.sub( prevTouch ).lengthSq() > rotateOrZoomThreshold && scope.rotateEnabled ) {
	//       scope.rotate( touch.sub( prevTouch ).multiplyScalar( - 0.005 ) );
  //     } else {
	//       var dx = touches[ 0 ].pageX - touches[ 1 ].pageX;
	//       var dy = touches[ 0 ].pageY - touches[ 1 ].pageY;
	//       var distance = Math.sqrt( dx * dx + dy * dy ) * zoomSpeed;
	//       scope.zoom( new THREE.Vector3( 0, 0, prevDistance - distance ) );
	//       prevDistance = distance;
  //     }
	//     prevTouch.set( cx, cy, 0 );
	//     break;

	//   case 3:
	//     touch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
	//     scope.pan( touch.sub( prevTouch ).setX( - touch.x ) );
	//     prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );
	//     break;

	//   }

	//   // prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );

  // }


  // touch

	var touch = new THREE.Vector3();
	var prevTouch = new THREE.Vector3();
	var prevDistance = null;

	function touchStart( event ) {

		if ( scope.enabled === false ) return;

		var touches = event.touches;

		switch ( touches.length ) {
      case 1:
      // if ( scope.sketching ) {
      //   scope.emit( 'sketchStart' );
      // }
			case 2:
				var dx = touches[ 0 ].pageX - touches[ 1 ].pageX;
				var dy = touches[ 0 ].pageY - touches[ 1 ].pageY;
				prevDistance = Math.sqrt( dx * dx + dy * dy );
				break;

		}

		prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );

	}

	function touchMove( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();
		event.stopPropagation();

		var touches = event.touches;

		touch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );

		switch ( touches.length ) {

			case 1:
      // if ( scope.sketching ) {
        // touchSketching( event );
      // } else {
				scope.rotate( touch.sub( prevTouch ).multiplyScalar( - 0.005 ) );
      // }
				break;

			case 2:
				var dx = touches[ 0 ].pageX - touches[ 1 ].pageX;
				var dy = touches[ 0 ].pageY - touches[ 1 ].pageY;
				var distance = Math.sqrt( dx * dx + dy * dy );
				scope.zoom( new THREE.Vector3( 0, 0, prevDistance - distance ) );
				prevDistance = distance;
				break;

			case 3:
				scope.pan( touch.sub( prevTouch ).setX( - touch.x ) );
				break;

		}

		prevTouch.set( touches[ 0 ].pageX, touches[ 0 ].pageY, 0 );

	}

  // function touchEnd( event ) {
    // if ( scope.enabled === false ) return;
    // if ( scope.sketching ) {
      // oneStroke();
    // }
	  // state = STATE.NONE;
  // }

	// domElement.addEventListener( 'touchstart', touchStart, false );
	// domElement.addEventListener( 'touchmove', touchMove, false );


  this.enable();

  return this;
};
示例#12
0
    // XXX dont do this
    obj[nodeId] = true;

    return obj;
  },

  getIncoming: function(nodeId) {

    return this.getAdjacents(nodeId, 'in');
  },

  getOutgoing: function(nodeId) {

    return this.getAdjacents(nodeId, 'out');
  }
}

Graph.fn = Graph.prototype;

Emitter(Graph.prototype);

var currentMousePos = { x: -1, y: -1 };
d3.select(window).on("mousemove", function(d) {
  var ev = d3.event;
  currentMousePos.x = ev.pageX;
  currentMousePos.y = ev.pageY;
});

module.exports = Graph;
示例#13
0
文件: index.js 项目: segmentio/tip
  this.delay = options.delay || 300;
  this.el = html.cloneNode(true);
  this.events = events(this.el, this);
  this.winEvents = events(window, this);
  this.classes = classes(this.el);
  this.inner = query('.tip-inner', this.el);
  this.message(content);
  this.position('top');
  if (Tip.effect) this.effect(Tip.effect);
}

/**
 * Mixin emitter.
 */

Emitter(Tip.prototype);

/**
 * Set tip `content`.
 *
 * @param {String|jQuery|Element} content
 * @return {Tip} self
 * @api public
 */

Tip.prototype.message = function(content){
  this.inner.innerHTML = content;
  return this;
};

/**
示例#14
0
文件: index.js 项目: mephux/viewport
}

/**
 * Events
 */
on(RESIZE, function () { resized = true; });
on(SCROLL, function () { scrolled = true; });

/**
 * Viewport
 */
function Viewport() {
    this.init();
}

Emitter(Viewport.prototype);

Viewport.prototype.init = function () {
    var that = this;

    that.refresh();
    that.calculateDeviceDimensions();

    win.setInterval(function () {
        update.call(that);
    }, 350);
};

Viewport.prototype.device = {};
Viewport.prototype.cordinate = {};
require.register("ui-checkbox/index.js", function(exports, require, module){
var classes = require('classes'),
	domify = require('domify'),
	Emitter = require('emitter'),
	events = require('events'),
	prevent = require('prevent'),
	stop = require('stop'),
	template = require('./templates/template.html');


module.exports = UICheckbox;

/**
 * @class UICheckbox
 * Input Checkbox
 *
 * @constructor
 * Creates a new Checkbox instance.
 * @param {HTMLElement} [el] The input HTML element.
 */
function UICheckbox(el) {
	this.el = el || domify(template);

	this.init();
}


var fn = UICheckbox.prototype;
Emitter(fn);

fn.init = function() {
	this.checkbox = this.el.querySelector('input');

	if (!this.checkbox) { return this; }

	this.classes = classes(this.el);
	this.events();

	if (this.checkbox.checked) {
		this.check();
	} else {
		this.uncheck();
	}

	return this;
};

fn.events = function() {
	this.elEvents = events(this.el, this);
	this.elEvents.bind('click', 'onCheck');
};

fn.check = function() {
	this.checkbox.checked = true;
	this.classes
		.remove('ui-checkbox-unchecked')
		.add('ui-checkbox-checked');

	this.emit('change', true);

	return this;
};

fn.uncheck = function() {
	this.checkbox.checked = false;
	this.classes
		.remove('ui-checkbox-checked')
		.add('ui-checkbox-unchecked');

	this.emit('change', false);
	return this;
};

fn.toggle = function() {
	if (this.checkbox.checked) {
		this.uncheck();
	} else {
		this.check();
	}

	return this;
};

fn.name = function(name) {
	if (!name) {
		return this.checkbox.name;
	}

	this.checkbox.name = name;
	return this;
};

fn.onCheck = function(e) {
	prevent(e);
	stop(e);

	this.toggle();
};

fn.unbind = function() {
	this.elEvents.unbind('click', 'onCheck');
};

fn.destroy = fn.unbind;

fn.isChecked = function() {
	return this.checkbox.checked;
};

fn.val = fn.isChecked;
});
示例#16
0
    return new Infinite(el, loadCallback, margin);

  this.el = el;
  if(typeof loadCallback == "function")
    this.on("load", bind(this.el, loadCallback));
  
  this.margin = typeof margin == "number" ? margin : 0;
  this.iteration = 0;
  this.paused = false;

  // listen on scroll event
  this.bind(this.el);
}

// Inherit from Emitter
Emitter(Infinite.prototype);

/**
 * Bind to a DOMElement.
 *
 * @param {Object} el
 * @api public
 */

Infinite.prototype.bind = function(el) {
  if(el) this.el = el;

  this.unbind();
  this.events = events(this.el, this);

  if(this.el.scrollHeight > this.el.clientHeight) this.events.bind("scroll");
示例#17
0
  if (!(this instanceof StatsView)) return new StatsView(graph);
  var self = this;
  this.el = domify(template);
  this.set('description', '');
  this.set('repo', '');
  this.set('deps', 0);
  this.set('size', 0);
  this.set('sloc', 0);
  reactive(this.el, this, this);
}

/**
 * Mixin
 */

Emitter(StatsView.prototype);

/**
 * Set `prop` to `val`.
 *
 * @param {String} prop
 * @param {String} val
 * @return {StatsView}
 * @api public
 */

StatsView.prototype.set = function(prop, val){
  this[prop] = val;
  this.emit('change ' + prop);
  return this;
};
示例#18
0
function TimeSync(channel){
  if( !(this instanceof TimeSync) ){
    return new TimeSync(channel);
  }
  this.channel = channel;
  this.times = [];
  this.received = 0;
  this.index = 0;
  this.wanted = 32;
  this.requestTimes = {};
  this.timeout = 10000;
  this.interval = 160;
}

Emitter(TimeSync.prototype);

TimeSync.prototype.onmessage = function(msg){
  // wrap in typed array
  msg = new Uint8Array(msg);

  // check for REQUEST
  if( is(REQ,msg) ){
    var index = parse(msg)
    debug('got REQUEST',index)
    this.channel.send(write(REP,index))
    this.emit('request',index)
    return true;

  // check for REPLY
  } else if( is(REP,msg) ){
示例#19
0
 * @public
 */

function Recurly (options) {
  this.id = 0;
  this.version = version;
  this.configured = false;
  this.config = merge({}, defaults);
  if (options) this.configure(options);
}

/**
 * Inherits `Emitter`.
 */

Emitter(Recurly.prototype);

/**
 * Configure settings.
 *
 * @param {String|Object} options Either publicKey or object containing
 *                                publicKey and other optional members
 * @param {String} options.publicKey
 * @param {String} [options.currency]
 * @param {String} [options.api]
 * @public
 */

Recurly.prototype.configure = function configure (options) {
  if (this.configured) throw errors('already-configured');
示例#20
0
require.register("simpleio/lib/client/Client.js", function(exports, require, module){
var Emitter = require('emitter'),
    sio = require('./index'),
    Multiplexer = require('../shared/Multiplexer'),
    $ = require('../shared/utils');

/**
 * Client constructor.
 * Inherits from Emitter.
 *
 * @param {Object} options
 * @see Emitter
 * @api public
 */
function Client(options) {
    var self = this;

    this.options = $.extend({}, Client.options, options);
    this.ajax = this.options.ajax;
    this._multiplexer = new Multiplexer({duration: this.options.multiplexDuration})
        .on('reset', function() {
            self._open(true);
        });

    this._connections = 0;
    this._delivered = [];
    this._reconnectionAttempts = 1;
    this._id = $.uid();
}

/**
 * Default options, will be overwritten by options passed to the constructor.
 *
 *   - `ajax` required jQuery ajax api (web client only)
 *   - `url` connection url, default is `/simpleio`
 *   - `reconnectionDelay` ms amount to wait before to reconnect in case of error,
 *     will be increased on every further error until maxReconnectionDelay, default is `1000`
 *   - `maxReconnectionDelay` max ms amount to wait before to reconnect in case of error,
 *     default is `10000`
 *   - `multiplexDuration` ms amount for multiplexing messages before emitting,
 *     default is `500`
 *
 * @type {Object}
 * @api public
 */
Client.options = {
    url: '/simpleio',
    ajax: null,
    reconnectionDelay: 1000,
    maxReconnectionDelay: 10000,
    multiplexDuration: 500,
    ajaxOptions: {
        cache: false,
        dataType: 'json',
        async: true,
        global: false,
        // Server will close request if needed, ensure here
        // not using settings from global setup.
        timeout: 1000 * 60 * 2,

        // Define complete callback to overwrite the same from the global setup
        // and to avoid conflicts.
        complete: $.noop,
        simpleio: true
    }
};

Emitter(Client.prototype);
module.exports = Client;

/**
 * Start polling.
 *
 * @param {Object} [data] data to send with every request.
 * @return {Client} this
 * @api public
 */
Client.prototype.connect = function(data) {
    if (!this._polling) {
        this._polling = true;
        this._defaultData = data;
        this._open(true);
    }

    return this;
};

/**
 * Stop polling.
 *
 * @return {Client} this
 * @api public
 */
Client.prototype.disconnect = function() {
    this._polling = false;
    if (this._xhr) {
        this._xhr.abort();
    }

    return this;
};

/**
 * Send message to the server.
 *
 * @param {Mixed} message message to send.
 * @param {Function} [callback] is called when message was send to the server without error.
 * @return {Client} this
 * @api public
 */
Client.prototype.send = function(message, callback) {
    this._multiplexer.add(message);
    if (callback) this.once('success', callback);

    return this;
};

/**
 * Open connection.
 *
 * @param {Boolean} [immediately] create request immediately.
 * @return {Client} this
 * @api private
 */
Client.prototype._open = function(immediately) {
    var self = this,
        data = this._defaultData ? $.extend({}, this._defaultData) : {};

    data.client = this._id;

    if (!this._polling) {
        return this;
    }

    // There is already open connection which will be closed at some point
    // and then multiplexed messages will be sent if immediately is not true.
    if (!immediately && this._connections > 0) {
        return this;
    }

    if (this._multiplexer.get().length) {
        data.messages = this._multiplexer.get();
        this._multiplexer.reset();
    }

    if (this._delivered.length) {
        data.delivered = this._delivered;
        this._delivered = [];
    }

    this._connections++;

    this._xhr = this.ajax($.extend({}, this.options.ajaxOptions, {
        url: this.options.url,
        type: data.messages || data.delivered ? 'post' : 'get',
        data: data,
        success: function(data, status, xhr) {
            self.emit('success', data, status, xhr);
            self._onSuccess(data);
        },
        error: function(xhr, status, error) {
            self.emit('error', xhr, status, error);
            self._onError(data);
        }
    }));

    return this;
};

/**
 * Reconnect with incrementally delay.
 *
 * @return {Client} this
 * @api private
 */
Client.prototype._reopen = function() {
    var self = this,
        delay;

    this._reconnectionAttempts++;
    delay = this._reconnectionAttempts * this.options.reconnectionDelay;
    delay = Math.min(delay, this.options.maxReconnectionDelay);

    setTimeout(function() {
        self._open();
    }, delay);

    return this;
};

/**
 * Handle xhr error. Roll back "messages" and "delivered" to send them again by
 * next reconnect.
 *
 * @param {Object} data data which was not delivered.
 * @return {Client} this
 * @api private
 */
Client.prototype._onError = function(data) {
    this._connections--;

    if (data.delivered) {
        this._delivered.push.apply(this._delivered, data.delivered);
    }
    if (data.messages) {
        this._multiplexer.add(data.messages);
    }

    this._reopen();
};

/**
 * Handle xhr success. Emit events, send delivery confirmation.
 *
 * @param {Object} data data which was not delivered.
 * @return {Client} this
 * @api private
 */
Client.prototype._onSuccess = function(data) {
    var self = this;

    this._connections--;
    this._reconnectionAttempts = 1;

    if (data.messages.length) {
        $.each(data.messages, function(message) {
            self._delivered.push(message.id);
            if (message.data.event) {
                self.emit(message.data.event, message.data.data);
            }
            self.emit('message', message);
        });
    }

    // Send delivery confirmation immediately.
    this._open(Boolean(this._delivered.length));
};

});
示例#21
0
/**
 * A socket.io Decoder instance
 *
 * @return {Object} decoder
 * @api public
 */

function Decoder() {
  this.reconstructor = null;
}

/**
 * Mix in `Emitter` with Decoder.
 */

Emitter(Decoder.prototype);

/**
 * Decodes an ecoded packet string into packet JSON.
 *
 * @param {String} obj - encoded packet
 * @return {Object} packet
 * @api public
 */

Decoder.prototype.add = function(obj) {
  var packet;
  if ('string' == typeof obj) {
    packet = decodeString(obj);
    if (exports.BINARY_EVENT == packet.type || exports.ACK == packet.type) { // binary packet's json
      this.reconstructor = new BinaryReconstructor(packet);
示例#22
0
require.register("simpleio/lib/shared/Multiplexer.js", function(exports, require, module){
 var Emitter,
    $ = require('./utils');

try {
    Emitter = require('emitter-component');
} catch(err) {
    Emitter = require('emitter');
}

/**
 * Multiplexer constructor.
 * Inherits from `Emitter`.
 *
 * @param {Object} opts
 *   - `duration` amount of time in ms to wait until emiting "reset" event if
 *     messages are collected.
 * @api public
 */
function Multiplexer(opts) {
    var self = this;
    this._messages = [];
    this._timeoutId = setInterval(function() {
        self.reset(true);
    }, opts.duration);
}


Emitter(Multiplexer.prototype);
module.exports = Multiplexer;

/**
 * Add message(s).
 *
 * @param {Mixed} messages
 * @return {Multiplexer} this
 * @api public
 */
Multiplexer.prototype.add = function(messages) {
    if ($.isArray(messages)) {
        this._messages.push.apply(this._messages, messages);
    } else if (messages) {
        this._messages.push(messages);
    }

    return this;
};

/**
 * Reset multiplexer, emit "reset" if there are messages.
 *
 * @param {Boolean} [emit] only emit "reset" if true.
 * @return {Multiplexer} this
 * @api public
 */
Multiplexer.prototype.reset = function(emit) {
    if (this._messages.length) {
        if (emit) this.emit('reset');
        this._messages = [];
    }

    return this;
};

/**
 * Get messages.
 *
 * @return {Array}
 * @api public
 */
Multiplexer.prototype.get = function() {
    return this._messages;
};

/**
 * Stop multiplexer
 *
 * @return {Multiplexer} this
 * @api public
 */
Multiplexer.prototype.stop = function() {
    clearInterval(this._timeoutId);
    this.removeAllListeners();

    return this;
};

});
示例#23
0
  this.events.bind('click td', 'cellclick');
  this.events.bind('click th', 'headerclick');
  this.render();
}

Grid.prototype.name = 'karlbohlmark-grid';

Grid.prototype.editable = function () {
  this.isEditable = true;
  var cells = [].slice.call(this.el.querySelectorAll('td'));
};

Grid.prototype.sortableHeaderTemplate = '<th data-sortable><a href="#sort/#{name}">#{title}</a></th>';
Grid.prototype.headerTemplate = '<th>#{title}</th>';

Emitter(Grid.prototype);

Grid.prototype.cellclick = function (e) {
  console.log('cellclick');
};

Grid.prototype.headerclick = function (e) {
  console.log('cellclick');
};

Grid.prototype.columns = function (columns) {
  this.columns = columns;
  var grid = this;
  this.columns.forEach(function (col) {
    col.template = (col.sortable ? grid.sortableHeaderTemplate : grid.headerTemplate);
  });
示例#24
0
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module){var Q=require("q"),request=require("./../node_modules/superagent/lib/client")||window.superagent,retain=require("./index")(Q,request);module.exports=window.retain=function(){return retain}},{"./../node_modules/superagent/lib/client":5,"./index":2,q:4}],2:[function(require,module){module.exports=function(Q,request){"use strict";function _new(record){var deferred=Q.defer();return request.post(this.config.url).send(record).set("Accept","application/json").end(function(error,res){_handler(deferred,res,record)}),deferred.promise}function _set(record){var deferred=Q.defer();return request.post(this.config.url+"/"+record.id).send(record).set("Accept","application/json").end(function(error,res){_handler(deferred,res,record)}),deferred.promise}function _find(record){var deferred=Q.defer();return request.get(this.config.url+"/"+record.id).set("Accept","application/json").end(function(error,res){_handler(deferred,res,record)}),deferred.promise}function _all(){var deferred=Q.defer();return request.get(this.config.url,function(res){_handler(deferred,res)}),deferred.promise}function _remove(record){var deferred=Q.defer();return request.del(this.config.url+"/"+record.id).set("Accept","application/json").end(function(res){_handler(deferred,res)}),deferred.promise}function _handler(deferred,res,record){res.error?deferred.reject(new Error(res.error)):(record&&_update(res.body,record),deferred.resolve(res.body))}function _update(props,record){for(var p in props)record[p]=props[p]}var api={};return api.config={url:""},api.new=_new,api.set=_set,api.find=_find,api.all=_all,api.remove=_remove,api}},{}],3:[function(require,module){function noop(){}var process=module.exports={};process.nextTick=function(){var canSetImmediate="undefined"!=typeof window&&window.setImmediate,canPost="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(canSetImmediate)return function(f){return window.setImmediate(f)};if(canPost){var queue=[];return window.addEventListener("message",function(ev){var source=ev.source;if((source===window||null===source)&&"process-tick"===ev.data&&(ev.stopPropagation(),queue.length>0)){var fn=queue.shift();fn()}},!0),function(fn){queue.push(fn),window.postMessage("process-tick","*")}}return function(fn){setTimeout(fn,0)}}(),process.title="browser",process.browser=!0,process.env={},process.argv=[],process.on=noop,process.once=noop,process.off=noop,process.emit=noop,process.binding=function(){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(){throw new Error("process.chdir is not supported")}},{}],4:[function(require,module,exports){(function(process){!function(definition){if("function"==typeof bootstrap)bootstrap("promise",definition);else if("object"==typeof exports)module.exports=definition();else if("function"==typeof define&&define.amd)define(definition);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeQ=definition}else Q=definition()}(function(){"use strict";function uncurryThis(f){return function(){return call.apply(f,arguments)}}function isObject(value){return value===Object(value)}function isStopIteration(exception){return"[object StopIteration]"===object_toString(exception)||exception instanceof QReturnValue}function makeStackTraceLong(error,promise){if(hasStacks&&promise.stack&&"object"==typeof error&&null!==error&&error.stack&&-1===error.stack.indexOf(STACK_JUMP_SEPARATOR)){for(var stacks=[],p=promise;p;p=p.source)p.stack&&stacks.unshift(p.stack);stacks.unshift(error.stack);var concatedStacks=stacks.join("\n"+STACK_JUMP_SEPARATOR+"\n");error.stack=filterStackString(concatedStacks)}}function filterStackString(stackString){for(var lines=stackString.split("\n"),desiredLines=[],i=0;i<lines.length;++i){var line=lines[i];isInternalFrame(line)||isNodeFrame(line)||!line||desiredLines.push(line)}return desiredLines.join("\n")}function isNodeFrame(stackLine){return-1!==stackLine.indexOf("(module.js:")||-1!==stackLine.indexOf("(node.js:")}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1)return[attempt1[1],Number(attempt1[2])];var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2)return[attempt2[1],Number(attempt2[2])];var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);return attempt3?[attempt3[1],Number(attempt3[2])]:void 0}function isInternalFrame(stackLine){var fileNameAndLineNumber=getFileNameAndLineNumber(stackLine);if(!fileNameAndLineNumber)return!1;var fileName=fileNameAndLineNumber[0],lineNumber=fileNameAndLineNumber[1];return fileName===qFileName&&lineNumber>=qStartingLine&&qEndingLine>=lineNumber}function captureLine(){if(hasStacks)try{throw new Error}catch(e){var lines=e.stack.split("\n"),firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2],fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber)return;return qFileName=fileNameAndLineNumber[0],fileNameAndLineNumber[1]}}function deprecate(callback,name,alternative){return function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(name+" is deprecated, use "+alternative+" instead.",new Error("").stack),callback.apply(callback,arguments)}}function Q(value){return isPromise(value)?value:isPromiseAlike(value)?coerce(value):fulfill(value)}function defer(){function become(newPromise){resolvedPromise=newPromise,promise.source=newPromise,array_reduce(messages,function(undefined,message){nextTick(function(){newPromise.promiseDispatch.apply(newPromise,message)})},void 0),messages=void 0,progressListeners=void 0}var resolvedPromise,messages=[],progressListeners=[],deferred=object_create(defer.prototype),promise=object_create(Promise.prototype);if(promise.promiseDispatch=function(resolve,op,operands){var args=array_slice(arguments);messages?(messages.push(args),"when"===op&&operands[1]&&progressListeners.push(operands[1])):nextTick(function(){resolvedPromise.promiseDispatch.apply(resolvedPromise,args)})},promise.valueOf=function(){if(messages)return promise;var nearerValue=nearer(resolvedPromise);return isPromise(nearerValue)&&(resolvedPromise=nearerValue),nearerValue},promise.inspect=function(){return resolvedPromise?resolvedPromise.inspect():{state:"pending"}},Q.longStackSupport&&hasStacks)try{throw new Error}catch(e){promise.stack=e.stack.substring(e.stack.indexOf("\n")+1)}return deferred.promise=promise,deferred.resolve=function(value){resolvedPromise||become(Q(value))},deferred.fulfill=function(value){resolvedPromise||become(fulfill(value))},deferred.reject=function(reason){resolvedPromise||become(reject(reason))},deferred.notify=function(progress){resolvedPromise||array_reduce(progressListeners,function(undefined,progressListener){nextTick(function(){progressListener(progress)})},void 0)},deferred}function promise(resolver){if("function"!=typeof resolver)throw new TypeError("resolver must be a function.");var deferred=defer();try{resolver(deferred.resolve,deferred.reject,deferred.notify)}catch(reason){deferred.reject(reason)}return deferred.promise}function race(answerPs){return promise(function(resolve,reject){for(var i=0,len=answerPs.length;len>i;i++)Q(answerPs[i]).then(resolve,reject)})}function Promise(descriptor,fallback,inspect){void 0===fallback&&(fallback=function(op){return reject(new Error("Promise does not support operation: "+op))}),void 0===inspect&&(inspect=function(){return{state:"unknown"}});var promise=object_create(Promise.prototype);if(promise.promiseDispatch=function(resolve,op,args){var result;try{result=descriptor[op]?descriptor[op].apply(promise,args):fallback.call(promise,op,args)}catch(exception){result=reject(exception)}resolve&&resolve(result)},promise.inspect=inspect,inspect){var inspected=inspect();"rejected"===inspected.state&&(promise.exception=inspected.reason),promise.valueOf=function(){var inspected=inspect();return"pending"===inspected.state||"rejected"===inspected.state?promise:inspected.value}}return promise}function when(value,fulfilled,rejected,progressed){return Q(value).then(fulfilled,rejected,progressed)}function nearer(value){if(isPromise(value)){var inspected=value.inspect();if("fulfilled"===inspected.state)return inspected.value}return value}function isPromise(object){return isObject(object)&&"function"==typeof object.promiseDispatch&&"function"==typeof object.inspect}function isPromiseAlike(object){return isObject(object)&&"function"==typeof object.then}function isPending(object){return isPromise(object)&&"pending"===object.inspect().state}function isFulfilled(object){return!isPromise(object)||"fulfilled"===object.inspect().state}function isRejected(object){return isPromise(object)&&"rejected"===object.inspect().state}function resetUnhandledRejections(){unhandledReasons.length=0,unhandledRejections.length=0,trackUnhandledRejections||(trackUnhandledRejections=!0)}function trackRejection(promise,reason){trackUnhandledRejections&&(unhandledRejections.push(promise),unhandledReasons.push(reason&&"undefined"!=typeof reason.stack?reason.stack:"(no stack) "+reason))}function untrackRejection(promise){if(trackUnhandledRejections){var at=array_indexOf(unhandledRejections,promise);-1!==at&&(unhandledRejections.splice(at,1),unhandledReasons.splice(at,1))}}function reject(reason){var rejection=Promise({when:function(rejected){return rejected&&untrackRejection(this),rejected?rejected(reason):this}},function(){return this},function(){return{state:"rejected",reason:reason}});return trackRejection(rejection,reason),rejection}function fulfill(value){return Promise({when:function(){return value},get:function(name){return value[name]},set:function(name,rhs){value[name]=rhs},"delete":function(name){delete value[name]},post:function(name,args){return null===name||void 0===name?value.apply(void 0,args):value[name].apply(value,args)},apply:function(thisp,args){return value.apply(thisp,args)},keys:function(){return object_keys(value)}},void 0,function(){return{state:"fulfilled",value:value}})}function coerce(promise){var deferred=defer();return nextTick(function(){try{promise.then(deferred.resolve,deferred.reject,deferred.notify)}catch(exception){deferred.reject(exception)}}),deferred.promise}function master(object){return Promise({isDef:function(){}},function(op,args){return dispatch(object,op,args)},function(){return Q(object).inspect()})}function spread(value,fulfilled,rejected){return Q(value).spread(fulfilled,rejected)}function async(makeGenerator){return function(){function continuer(verb,arg){var result;if("undefined"==typeof StopIteration){try{result=generator[verb](arg)}catch(exception){return reject(exception)}return result.done?result.value:when(result.value,callback,errback)}try{result=generator[verb](arg)}catch(exception){return isStopIteration(exception)?exception.value:reject(exception)}return when(result,callback,errback)}var generator=makeGenerator.apply(this,arguments),callback=continuer.bind(continuer,"next"),errback=continuer.bind(continuer,"throw");return callback()}}function spawn(makeGenerator){Q.done(Q.async(makeGenerator)())}function _return(value){throw new QReturnValue(value)}function promised(callback){return function(){return spread([this,all(arguments)],function(self,args){return callback.apply(self,args)})}}function dispatch(object,op,args){return Q(object).dispatch(op,args)}function all(promises){return when(promises,function(promises){var countDown=0,deferred=defer();return array_reduce(promises,function(undefined,promise,index){var snapshot;isPromise(promise)&&"fulfilled"===(snapshot=promise.inspect()).state?promises[index]=snapshot.value:(++countDown,when(promise,function(value){promises[index]=value,0===--countDown&&deferred.resolve(promises)},deferred.reject,function(progress){deferred.notify({index:index,value:progress})}))},void 0),0===countDown&&deferred.resolve(promises),deferred.promise})}function allResolved(promises){return when(promises,function(promises){return promises=array_map(promises,Q),when(all(array_map(promises,function(promise){return when(promise,noop,noop)})),function(){return promises})})}function allSettled(promises){return Q(promises).allSettled()}function progress(object,progressed){return Q(object).then(void 0,void 0,progressed)}function nodeify(object,nodeback){return Q(object).nodeify(nodeback)}var hasStacks=!1;try{throw new Error}catch(e){hasStacks=!!e.stack}var qFileName,QReturnValue,qStartingLine=captureLine(),noop=function(){},nextTick=function(){function flush(){for(;head.next;){head=head.next;var task=head.task;head.task=void 0;var domain=head.domain;domain&&(head.domain=void 0,domain.enter());try{task()}catch(e){if(isNodeJS)throw domain&&domain.exit(),setTimeout(flush,0),domain&&domain.enter(),e;setTimeout(function(){throw e},0)}domain&&domain.exit()}flushing=!1}var head={task:void 0,next:null},tail=head,flushing=!1,requestTick=void 0,isNodeJS=!1;if(nextTick=function(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null},flushing||(flushing=!0,requestTick())},"undefined"!=typeof process&&process.nextTick)isNodeJS=!0,requestTick=function(){process.nextTick(flush)};else if("function"==typeof setImmediate)requestTick="undefined"!=typeof window?setImmediate.bind(window,flush):function(){setImmediate(flush)};else if("undefined"!=typeof MessageChannel){var channel=new MessageChannel;channel.port1.onmessage=function(){requestTick=requestPortTick,channel.port1.onmessage=flush,flush()};var requestPortTick=function(){channel.port2.postMessage(0)};requestTick=function(){setTimeout(flush,0),requestPortTick()}}else requestTick=function(){setTimeout(flush,0)};return nextTick}(),call=Function.call,array_slice=uncurryThis(Array.prototype.slice),array_reduce=uncurryThis(Array.prototype.reduce||function(callback,basis){var index=0,length=this.length;if(1===arguments.length)for(;;){if(index in this){basis=this[index++];break}if(++index>=length)throw new TypeError}for(;length>index;index++)index in this&&(basis=callback(basis,this[index],index));return basis}),array_indexOf=uncurryThis(Array.prototype.indexOf||function(value){for(var i=0;i<this.length;i++)if(this[i]===value)return i;return-1}),array_map=uncurryThis(Array.prototype.map||function(callback,thisp){var self=this,collect=[];return array_reduce(self,function(undefined,value,index){collect.push(callback.call(thisp,value,index,self))},void 0),collect}),object_create=Object.create||function(prototype){function Type(){}return Type.prototype=prototype,new Type},object_hasOwnProperty=uncurryThis(Object.prototype.hasOwnProperty),object_keys=Object.keys||function(object){var keys=[];for(var key in object)object_hasOwnProperty(object,key)&&keys.push(key);return keys},object_toString=uncurryThis(Object.prototype.toString);QReturnValue="undefined"!=typeof ReturnValue?ReturnValue:function(value){this.value=value};var STACK_JUMP_SEPARATOR="From previous event:";Q.resolve=Q,Q.nextTick=nextTick,Q.longStackSupport=!1,Q.defer=defer,defer.prototype.makeNodeResolver=function(){var self=this;return function(error,value){error?self.reject(error):self.resolve(arguments.length>2?array_slice(arguments,1):value)}},Q.Promise=promise,Q.promise=promise,promise.race=race,promise.all=all,promise.reject=reject,promise.resolve=Q,Q.passByCopy=function(object){return object},Promise.prototype.passByCopy=function(){return this},Q.join=function(x,y){return Q(x).join(y)},Promise.prototype.join=function(that){return Q([this,that]).spread(function(x,y){if(x===y)return x;throw new Error("Can't join: not the same: "+x+" "+y)})},Q.race=race,Promise.prototype.race=function(){return this.then(Q.race)},Q.makePromise=Promise,Promise.prototype.toString=function(){return"[object Promise]"},Promise.prototype.then=function(fulfilled,rejected,progressed){function _fulfilled(value){try{return"function"==typeof fulfilled?fulfilled(value):value}catch(exception){return reject(exception)}}function _rejected(exception){if("function"==typeof rejected){makeStackTraceLong(exception,self);try{return rejected(exception)}catch(newException){return reject(newException)}}return reject(exception)}function _progressed(value){return"function"==typeof progressed?progressed(value):value}var self=this,deferred=defer(),done=!1;return nextTick(function(){self.promiseDispatch(function(value){done||(done=!0,deferred.resolve(_fulfilled(value)))},"when",[function(exception){done||(done=!0,deferred.resolve(_rejected(exception)))}])}),self.promiseDispatch(void 0,"when",[void 0,function(value){var newValue,threw=!1;try{newValue=_progressed(value)}catch(e){if(threw=!0,!Q.onerror)throw e;Q.onerror(e)}threw||deferred.notify(newValue)}]),deferred.promise},Q.when=when,Promise.prototype.thenResolve=function(value){return this.then(function(){return value})},Q.thenResolve=function(promise,value){return Q(promise).thenResolve(value)},Promise.prototype.thenReject=function(reason){return this.then(function(){throw reason})},Q.thenReject=function(promise,reason){return Q(promise).thenReject(reason)},Q.nearer=nearer,Q.isPromise=isPromise,Q.isPromiseAlike=isPromiseAlike,Q.isPending=isPending,Promise.prototype.isPending=function(){return"pending"===this.inspect().state},Q.isFulfilled=isFulfilled,Promise.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},Q.isRejected=isRejected,Promise.prototype.isRejected=function(){return"rejected"===this.inspect().state};var unhandledReasons=[],unhandledRejections=[],trackUnhandledRejections=!0;Q.resetUnhandledRejections=resetUnhandledRejections,Q.getUnhandledReasons=function(){return unhandledReasons.slice()},Q.stopUnhandledRejectionTracking=function(){resetUnhandledRejections(),trackUnhandledRejections=!1},resetUnhandledRejections(),Q.reject=reject,Q.fulfill=fulfill,Q.master=master,Q.spread=spread,Promise.prototype.spread=function(fulfilled,rejected){return this.all().then(function(array){return fulfilled.apply(void 0,array)},rejected)},Q.async=async,Q.spawn=spawn,Q["return"]=_return,Q.promised=promised,Q.dispatch=dispatch,Promise.prototype.dispatch=function(op,args){var self=this,deferred=defer();return nextTick(function(){self.promiseDispatch(deferred.resolve,op,args)}),deferred.promise},Q.get=function(object,key){return Q(object).dispatch("get",[key])},Promise.prototype.get=function(key){return this.dispatch("get",[key])},Q.set=function(object,key,value){return Q(object).dispatch("set",[key,value])},Promise.prototype.set=function(key,value){return this.dispatch("set",[key,value])},Q.del=Q["delete"]=function(object,key){return Q(object).dispatch("delete",[key])},Promise.prototype.del=Promise.prototype["delete"]=function(key){return this.dispatch("delete",[key])},Q.mapply=Q.post=function(object,name,args){return Q(object).dispatch("post",[name,args])},Promise.prototype.mapply=Promise.prototype.post=function(name,args){return this.dispatch("post",[name,args])},Q.send=Q.mcall=Q.invoke=function(object,name){return Q(object).dispatch("post",[name,array_slice(arguments,2)])},Promise.prototype.send=Promise.prototype.mcall=Promise.prototype.invoke=function(name){return this.dispatch("post",[name,array_slice(arguments,1)])},Q.fapply=function(object,args){return Q(object).dispatch("apply",[void 0,args])},Promise.prototype.fapply=function(args){return this.dispatch("apply",[void 0,args])},Q["try"]=Q.fcall=function(object){return Q(object).dispatch("apply",[void 0,array_slice(arguments,1)])},Promise.prototype.fcall=function(){return this.dispatch("apply",[void 0,array_slice(arguments)])},Q.fbind=function(object){var promise=Q(object),args=array_slice(arguments,1);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Promise.prototype.fbind=function(){var promise=this,args=array_slice(arguments);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Q.keys=function(object){return Q(object).dispatch("keys",[])},Promise.prototype.keys=function(){return this.dispatch("keys",[])},Q.all=all,Promise.prototype.all=function(){return all(this)},Q.allResolved=deprecate(allResolved,"allResolved","allSettled"),Promise.prototype.allResolved=function(){return allResolved(this)},Q.allSettled=allSettled,Promise.prototype.allSettled=function(){return this.then(function(promises){return all(array_map(promises,function(promise){function regardless(){return promise.inspect()}return promise=Q(promise),promise.then(regardless,regardless)}))})},Q.fail=Q["catch"]=function(object,rejected){return Q(object).then(void 0,rejected)},Promise.prototype.fail=Promise.prototype["catch"]=function(rejected){return this.then(void 0,rejected)},Q.progress=progress,Promise.prototype.progress=function(progressed){return this.then(void 0,void 0,progressed)},Q.fin=Q["finally"]=function(object,callback){return Q(object)["finally"](callback)},Promise.prototype.fin=Promise.prototype["finally"]=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall().then(function(){return value})},function(reason){return callback.fcall().then(function(){throw reason})})},Q.done=function(object,fulfilled,rejected,progress){return Q(object).done(fulfilled,rejected,progress)},Promise.prototype.done=function(fulfilled,rejected,progress){var onUnhandledError=function(error){nextTick(function(){if(makeStackTraceLong(error,promise),!Q.onerror)throw error;Q.onerror(error)})},promise=fulfilled||rejected||progress?this.then(fulfilled,rejected,progress):this;"object"==typeof process&&process&&process.domain&&(onUnhandledError=process.domain.bind(onUnhandledError)),promise.then(void 0,onUnhandledError)},Q.timeout=function(object,ms,message){return Q(object).timeout(ms,message)},Promise.prototype.timeout=function(ms,message){var deferred=defer(),timeoutId=setTimeout(function(){deferred.reject(new Error(message||"Timed out after "+ms+" ms"))},ms);return this.then(function(value){clearTimeout(timeoutId),deferred.resolve(value)},function(exception){clearTimeout(timeoutId),deferred.reject(exception)},deferred.notify),deferred.promise},Q.delay=function(object,timeout){return void 0===timeout&&(timeout=object,object=void 0),Q(object).delay(timeout)},Promise.prototype.delay=function(timeout){return this.then(function(value){var deferred=defer();return setTimeout(function(){deferred.resolve(value)},timeout),deferred.promise})},Q.nfapply=function(callback,args){return Q(callback).nfapply(args)},Promise.prototype.nfapply=function(args){var deferred=defer(),nodeArgs=array_slice(args);return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfcall=function(callback){var args=array_slice(arguments,1);return Q(callback).nfapply(args)},Promise.prototype.nfcall=function(){var nodeArgs=array_slice(arguments),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfbind=Q.denodeify=function(callback){var baseArgs=array_slice(arguments,1);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(callback).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nfbind=Promise.prototype.denodeify=function(){var args=array_slice(arguments);return args.unshift(this),Q.denodeify.apply(void 0,args)},Q.nbind=function(callback,thisp){var baseArgs=array_slice(arguments,2);return function(){function bound(){return callback.apply(thisp,arguments)}var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(bound).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nbind=function(){var args=array_slice(arguments,0);return args.unshift(this),Q.nbind.apply(void 0,args)},Q.nmapply=Q.npost=function(object,name,args){return Q(object).npost(name,args)},Promise.prototype.nmapply=Promise.prototype.npost=function(name,args){var nodeArgs=array_slice(args||[]),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nsend=Q.nmcall=Q.ninvoke=function(object,name){var nodeArgs=array_slice(arguments,2),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(object).dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Promise.prototype.nsend=Promise.prototype.nmcall=Promise.prototype.ninvoke=function(name){var nodeArgs=array_slice(arguments,1),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nodeify=nodeify,Promise.prototype.nodeify=function(nodeback){return nodeback?void this.then(function(value){nextTick(function(){nodeback(null,value)})},function(error){nextTick(function(){nodeback(error)})}):this};var qEndingLine=captureLine();return Q})}).call(this,require("/Users/giuliandrimba/codes/retain-http/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"))},{"/Users/giuliandrimba/codes/retain-http/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":3}],5:[function(require,module){function noop(){}function isHost(obj){var str={}.toString.call(obj);switch(str){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}}function getXHR(){if(root.XMLHttpRequest&&("file:"!=root.location.protocol||!root.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}return!1}function isObject(obj){return obj===Object(obj)}function serialize(obj){if(!isObject(obj))return obj;var pairs=[];for(var key in obj)null!=obj[key]&&pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));return pairs.join("&")}function parseString(str){for(var parts,pair,obj={},pairs=str.split("&"),i=0,len=pairs.length;len>i;++i)pair=pairs[i],parts=pair.split("="),obj[decodeURIComponent(parts[0])]=decodeURIComponent(parts[1]);return obj}function parseHeader(str){var index,line,field,val,lines=str.split(/\r?\n/),fields={};lines.pop();for(var i=0,len=lines.length;len>i;++i)line=lines[i],index=line.indexOf(":"),field=line.slice(0,index).toLowerCase(),val=trim(line.slice(index+1)),fields[field]=val;return fields}function type(str){return str.split(/ *; */).shift()}function params(str){return reduce(str.split(/ *; */),function(obj,str){var parts=str.split(/ *= */),key=parts.shift(),val=parts.shift();return key&&val&&(obj[key]=val),obj},{})}function Response(req,options){options=options||{},this.req=req,this.xhr=this.req.xhr,this.text=this.xhr.responseText,this.setStatusProperties(this.xhr.status),this.header=this.headers=parseHeader(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this.setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this.parseBody(this.text):null}function Request(method,url){var self=this;Emitter.call(this),this._query=this._query||[],this.method=method,this.url=url,this.header={},this._header={},this.on("end",function(){var res=new Response(self);"HEAD"==method&&(res.text=null),self.callback(null,res)})}function request(method,url){return"function"==typeof url?new Request("GET",method).end(url):1==arguments.length?new Request("GET",method):new Request(method,url)}var Emitter=require("emitter"),reduce=require("reduce"),root="undefined"==typeof window?this:window,trim="".trim?function(s){return s.trim()}:function(s){return s.replace(/(^\s*|\s*$)/g,"")};request.serializeObject=serialize,request.parseString=parseString,request.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},request.serialize={"application/x-www-form-urlencoded":serialize,"application/json":JSON.stringify},request.parse={"application/x-www-form-urlencoded":parseString,"application/json":JSON.parse},Response.prototype.get=function(field){return this.header[field.toLowerCase()]},Response.prototype.setHeaderProperties=function(){var ct=this.header["content-type"]||"";this.type=type(ct);var obj=params(ct);for(var key in obj)this[key]=obj[key]},Response.prototype.parseBody=function(str){var parse=request.parse[this.type];return parse?parse(str):null},Response.prototype.setStatusProperties=function(status){var type=status/100|0;this.status=status,this.statusType=type,this.info=1==type,this.ok=2==type,this.clientError=4==type,this.serverError=5==type,this.error=4==type||5==type?this.toError():!1,this.accepted=202==status,this.noContent=204==status||1223==status,this.badRequest=400==status,this.unauthorized=401==status,this.notAcceptable=406==status,this.notFound=404==status,this.forbidden=403==status},Response.prototype.toError=function(){var req=this.req,method=req.method,path=req.path,msg="cannot "+method+" "+path+" ("+this.status+")",err=new Error(msg);return err.status=this.status,err.method=method,err.path=path,err},request.Response=Response,Emitter(Request.prototype),Request.prototype.timeout=function(ms){return this._timeout=ms,this},Request.prototype.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},Request.prototype.abort=function(){return this.aborted?void 0:(this.aborted=!0,this.xhr.abort(),this.clearTimeout(),this.emit("abort"),this)},Request.prototype.set=function(field,val){if(isObject(field)){for(var key in field)this.set(key,field[key]);return this}return this._header[field.toLowerCase()]=val,this.header[field]=val,this},Request.prototype.getHeader=function(field){return this._header[field.toLowerCase()]},Request.prototype.type=function(type){return this.set("Content-Type",request.types[type]||type),this},Request.prototype.accept=function(type){return this.set("Accept",request.types[type]||type),this},Request.prototype.auth=function(user,pass){var str=btoa(user+":"+pass);return this.set("Authorization","Basic "+str),this},Request.prototype.query=function(val){return"string"!=typeof val&&(val=serialize(val)),val&&this._query.push(val),this},Request.prototype.send=function(data){var obj=isObject(data),type=this.getHeader("Content-Type");if(obj&&isObject(this._data))for(var key in data)this._data[key]=data[key];else"string"==typeof data?(type||this.type("form"),type=this.getHeader("Content-Type"),this._data="application/x-www-form-urlencoded"==type?this._data?this._data+"&"+data:data:(this._data||"")+data):this._data=data;return obj?(type||this.type("json"),this):this},Request.prototype.callback=function(err,res){var fn=this._callback;return 2==fn.length?fn(err,res):err?this.emit("error",err):void fn(res)},Request.prototype.crossDomainError=function(){var err=new Error("Origin is not allowed by Access-Control-Allow-Origin");err.crossDomain=!0,this.callback(err)},Request.prototype.timeoutError=function(){var timeout=this._timeout,err=new Error("timeout of "+timeout+"ms exceeded");err.timeout=timeout,this.callback(err)},Request.prototype.withCredentials=function(){return this._withCredentials=!0,this},Request.prototype.end=function(fn){var self=this,xhr=this.xhr=getXHR(),query=this._query.join("&"),timeout=this._timeout,data=this._data;if(this._callback=fn||noop,xhr.onreadystatechange=function(){return 4==xhr.readyState?0==xhr.status?self.aborted?self.timeoutError():self.crossDomainError():void self.emit("end"):void 0
},xhr.upload&&(xhr.upload.onprogress=function(e){e.percent=e.loaded/e.total*100,self.emit("progress",e)}),timeout&&!this._timer&&(this._timer=setTimeout(function(){self.abort()},timeout)),query&&(query=request.serializeObject(query),this.url+=~this.url.indexOf("?")?"&"+query:"?"+query),xhr.open(this.method,this.url,!0),this._withCredentials&&(xhr.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof data&&!isHost(data)){var serialize=request.serialize[this.getHeader("Content-Type")];serialize&&(data=serialize(data))}for(var field in this.header)null!=this.header[field]&&xhr.setRequestHeader(field,this.header[field]);return xhr.send(data),this},request.Request=Request,request.get=function(url,data,fn){var req=request("GET",url);return"function"==typeof data&&(fn=data,data=null),data&&req.query(data),fn&&req.end(fn),req},request.head=function(url,data,fn){var req=request("HEAD",url);return"function"==typeof data&&(fn=data,data=null),data&&req.send(data),fn&&req.end(fn),req},request.del=function(url,fn){var req=request("DELETE",url);return fn&&req.end(fn),req},request.patch=function(url,data,fn){var req=request("PATCH",url);return"function"==typeof data&&(fn=data,data=null),data&&req.send(data),fn&&req.end(fn),req},request.post=function(url,data,fn){var req=request("POST",url);return"function"==typeof data&&(fn=data,data=null),data&&req.send(data),fn&&req.end(fn),req},request.put=function(url,data,fn){var req=request("PUT",url);return"function"==typeof data&&(fn=data,data=null),data&&req.send(data),fn&&req.end(fn),req},module.exports=request},{emitter:6,reduce:7}],6:[function(require,module){function Emitter(obj){return obj?mixin(obj):void 0}function mixin(obj){for(var key in Emitter.prototype)obj[key]=Emitter.prototype[key];return obj}module.exports=Emitter,Emitter.prototype.on=function(event,fn){return this._callbacks=this._callbacks||{},(this._callbacks[event]=this._callbacks[event]||[]).push(fn),this},Emitter.prototype.once=function(event,fn){function on(){self.off(event,on),fn.apply(this,arguments)}var self=this;return this._callbacks=this._callbacks||{},fn._off=on,this.on(event,on),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=function(event,fn){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length)return delete this._callbacks[event],this;var i=callbacks.indexOf(fn._off||fn);return~i&&callbacks.splice(i,1),this},Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;len>i;++i)callbacks[i].apply(this,args)}return this},Emitter.prototype.listeners=function(event){return this._callbacks=this._callbacks||{},this._callbacks[event]||[]},Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],7:[function(require,module){module.exports=function(arr,fn,initial){for(var idx=0,len=arr.length,curr=3==arguments.length?initial:arr[idx++];len>idx;)curr=fn.call(null,curr,arr[idx],++idx,arr);return curr}},{}]},{},[1]);
示例#25
0
  this.state('initializing');
  this.initialize();

  laws.on('loaded', this.onlawsready)

  //TODO: make all this dependent on `bus` when making views reactive in #284
  citizen.on('loaded', this.refresh);
  citizen.on('unloaded', this.reset);
}

/**
 * Mixin `LawsFilter` with `Emitter`
 */

Emitter(LawsFilter.prototype);

LawsFilter.prototype.initialize = function() {
  this.$_items = [];
  this.$_filters = {};
  this.$_counts = [];
  this.sorts = sorts;
  // TODO: remove this hardcode and use a default sort (maybe by config?)
  this.$_filters['sort'] = 'closing-soon';
  this.$_filters['status'] = 'open';
  this.sort = sorts[this.get('sort')];
};

LawsFilter.prototype.refresh = function() {
  laws.ready(this.fetch);
}
示例#26
0
文件: proto.js 项目: actano/model
try {
  var Emitter = require('emitter');
  var each = require('each');
} catch (e) {
  var Emitter = require('component-emitter');
  var each = require('component-each');
}

var request = require('superagent');
var noop = function(){};

/**
 * Mixin emitter.
 */

Emitter(exports);

/**
 * Expose request for configuration
 */
exports.request = request;

/**
 * Register an error `msg` on `attr`.
 *
 * @param {String} attr
 * @param {String} msg
 * @return {Object} self
 * @api public
 */
示例#27
0
  this.on('showing', function(){
    document.body.appendChild(el);
  });

  this.on('hide', function(){
    document.body.removeChild(el);
  });
}


/**
 * Mixin emitter.
 */

Emitter(Modal.prototype);
Showable(Modal.prototype);
Classes(Modal.prototype);


/**
 * Set the transition in/out effect
 *
 * @param {String} type
 *
 * @return {Modal}
 */

Modal.prototype.effect = function(type) {
  this.el.setAttribute('effect', type);
  return this;
示例#28
0
  }));

  // emit "next"
  events.bind(this.el.querySelector('.next'), 'click', normalize(function(ev){
    ev.preventDefault();

    self.emit('next');
    return false;
  }));
}

/**
 * Mixin emitter.
 */

Emitter(Days.prototype);

/**
 * Select the given `date`.
 *
 * @param {Date} date
 * @return {Days}
 * @api public
 */

Days.prototype.select = function(date){
  this.selected = date;
  return this;
};

示例#29
0
文件: annie.js 项目: neonaleon/annie
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
 * Module dependencies.
 */

var Emitter = require('emitter');
var reduce = require('reduce');

/**
 * Root reference for iframes.
 */

var root = 'undefined' == typeof window
  ? this
  : window;

/**
 * Noop.
 */

function noop(){};

/**
 * Check if `obj` is a host object,
 * we don't want to serialize these :)
 *
 * TODO: future proof, move to compoent land
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isHost(obj) {
  var str = {}.toString.call(obj);

  switch (str) {
    case '[object File]':
    case '[object Blob]':
    case '[object FormData]':
      return true;
    default:
      return false;
  }
}

/**
 * Determine XHR.
 */

function getXHR() {
  if (root.XMLHttpRequest
    && ('file:' != root.location.protocol || !root.ActiveXObject)) {
    return new XMLHttpRequest;
  } else {
    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
  }
  return false;
}

/**
 * Removes leading and trailing whitespace, added to support IE.
 *
 * @param {String} s
 * @return {String}
 * @api private
 */

var trim = ''.trim
  ? function(s) { return s.trim(); }
  : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };

/**
 * Check if `obj` is an object.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isObject(obj) {
  return obj === Object(obj);
}

/**
 * Serialize the given `obj`.
 *
 * @param {Object} obj
 * @return {String}
 * @api private
 */

function serialize(obj) {
  if (!isObject(obj)) return obj;
  var pairs = [];
  for (var key in obj) {
    if (null != obj[key]) {
      pairs.push(encodeURIComponent(key)
        + '=' + encodeURIComponent(obj[key]));
    }
  }
  return pairs.join('&');
}

/**
 * Expose serialization method.
 */

 request.serializeObject = serialize;

 /**
  * Parse the given x-www-form-urlencoded `str`.
  *
  * @param {String} str
  * @return {Object}
  * @api private
  */

function parseString(str) {
  var obj = {};
  var pairs = str.split('&');
  var parts;
  var pair;

  for (var i = 0, len = pairs.length; i < len; ++i) {
    pair = pairs[i];
    parts = pair.split('=');
    obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
  }

  return obj;
}

/**
 * Expose parser.
 */

request.parseString = parseString;

/**
 * Default MIME type map.
 *
 *     superagent.types.xml = 'application/xml';
 *
 */

request.types = {
  html: 'text/html',
  json: 'application/json',
  xml: 'application/xml',
  urlencoded: 'application/x-www-form-urlencoded',
  'form': 'application/x-www-form-urlencoded',
  'form-data': 'application/x-www-form-urlencoded'
};

/**
 * Default serialization map.
 *
 *     superagent.serialize['application/xml'] = function(obj){
 *       return 'generated xml here';
 *     };
 *
 */

 request.serialize = {
   'application/x-www-form-urlencoded': serialize,
   'application/json': JSON.stringify
 };

 /**
  * Default parsers.
  *
  *     superagent.parse['application/xml'] = function(str){
  *       return { object parsed from str };
  *     };
  *
  */

request.parse = {
  'application/x-www-form-urlencoded': parseString,
  'application/json': JSON.parse
};

/**
 * Parse the given header `str` into
 * an object containing the mapped fields.
 *
 * @param {String} str
 * @return {Object}
 * @api private
 */

function parseHeader(str) {
  var lines = str.split(/\r?\n/);
  var fields = {};
  var index;
  var line;
  var field;
  var val;

  lines.pop(); // trailing CRLF

  for (var i = 0, len = lines.length; i < len; ++i) {
    line = lines[i];
    index = line.indexOf(':');
    field = line.slice(0, index).toLowerCase();
    val = trim(line.slice(index + 1));
    fields[field] = val;
  }

  return fields;
}

/**
 * Return the mime type for the given `str`.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

function type(str){
  return str.split(/ *; */).shift();
};

/**
 * Return header field parameters.
 *
 * @param {String} str
 * @return {Object}
 * @api private
 */

function params(str){
  return reduce(str.split(/ *; */), function(obj, str){
    var parts = str.split(/ *= */)
      , key = parts.shift()
      , val = parts.shift();

    if (key && val) obj[key] = val;
    return obj;
  }, {});
};

/**
 * Initialize a new `Response` with the given `xhr`.
 *
 *  - set flags (.ok, .error, etc)
 *  - parse header
 *
 * Examples:
 *
 *  Aliasing `superagent` as `request` is nice:
 *
 *      request = superagent;
 *
 *  We can use the promise-like API, or pass callbacks:
 *
 *      request.get('/').end(function(res){});
 *      request.get('/', function(res){});
 *
 *  Sending data can be chained:
 *
 *      request
 *        .post('/user')
 *        .send({ name: 'tj' })
 *        .end(function(res){});
 *
 *  Or passed to `.send()`:
 *
 *      request
 *        .post('/user')
 *        .send({ name: 'tj' }, function(res){});
 *
 *  Or passed to `.post()`:
 *
 *      request
 *        .post('/user', { name: 'tj' })
 *        .end(function(res){});
 *
 * Or further reduced to a single call for simple cases:
 *
 *      request
 *        .post('/user', { name: 'tj' }, function(res){});
 *
 * @param {XMLHTTPRequest} xhr
 * @param {Object} options
 * @api private
 */

function Response(req, options) {
  options = options || {};
  this.req = req;
  this.xhr = this.req.xhr;
  this.text = this.xhr.responseText;
  this.setStatusProperties(this.xhr.status);
  this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
  // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
  // getResponseHeader still works. so we get content-type even if getting
  // other headers fails.
  this.header['content-type'] = this.xhr.getResponseHeader('content-type');
  this.setHeaderProperties(this.header);
  this.body = this.req.method != 'HEAD'
    ? this.parseBody(this.text)
    : null;
}

/**
 * Get case-insensitive `field` value.
 *
 * @param {String} field
 * @return {String}
 * @api public
 */

Response.prototype.get = function(field){
  return this.header[field.toLowerCase()];
};

/**
 * Set header related properties:
 *
 *   - `.type` the content type without params
 *
 * A response of "Content-Type: text/plain; charset=utf-8"
 * will provide you with a `.type` of "text/plain".
 *
 * @param {Object} header
 * @api private
 */

Response.prototype.setHeaderProperties = function(header){
  // content-type
  var ct = this.header['content-type'] || '';
  this.type = type(ct);

  // params
  var obj = params(ct);
  for (var key in obj) this[key] = obj[key];
};

/**
 * Parse the given body `str`.
 *
 * Used for auto-parsing of bodies. Parsers
 * are defined on the `superagent.parse` object.
 *
 * @param {String} str
 * @return {Mixed}
 * @api private
 */

Response.prototype.parseBody = function(str){
  var parse = request.parse[this.type];
  return parse && str && str.length
    ? parse(str)
    : null;
};

/**
 * Set flags such as `.ok` based on `status`.
 *
 * For example a 2xx response will give you a `.ok` of __true__
 * whereas 5xx will be __false__ and `.error` will be __true__. The
 * `.clientError` and `.serverError` are also available to be more
 * specific, and `.statusType` is the class of error ranging from 1..5
 * sometimes useful for mapping respond colors etc.
 *
 * "sugar" properties are also defined for common cases. Currently providing:
 *
 *   - .noContent
 *   - .badRequest
 *   - .unauthorized
 *   - .notAcceptable
 *   - .notFound
 *
 * @param {Number} status
 * @api private
 */

Response.prototype.setStatusProperties = function(status){
  var type = status / 100 | 0;

  // status / class
  this.status = status;
  this.statusType = type;

  // basics
  this.info = 1 == type;
  this.ok = 2 == type;
  this.clientError = 4 == type;
  this.serverError = 5 == type;
  this.error = (4 == type || 5 == type)
    ? this.toError()
    : false;

  // sugar
  this.accepted = 202 == status;
  this.noContent = 204 == status || 1223 == status;
  this.badRequest = 400 == status;
  this.unauthorized = 401 == status;
  this.notAcceptable = 406 == status;
  this.notFound = 404 == status;
  this.forbidden = 403 == status;
};

/**
 * Return an `Error` representative of this response.
 *
 * @return {Error}
 * @api public
 */

Response.prototype.toError = function(){
  var req = this.req;
  var method = req.method;
  var url = req.url;

  var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
  var err = new Error(msg);
  err.status = this.status;
  err.method = method;
  err.url = url;

  return err;
};

/**
 * Expose `Response`.
 */

request.Response = Response;

/**
 * Initialize a new `Request` with the given `method` and `url`.
 *
 * @param {String} method
 * @param {String} url
 * @api public
 */

function Request(method, url) {
  var self = this;
  Emitter.call(this);
  this._query = this._query || [];
  this.method = method;
  this.url = url;
  this.header = {};
  this._header = {};
  this.on('end', function(){
    try {
      var res = new Response(self);
      if ('HEAD' == method) res.text = null;
      self.callback(null, res);
    } catch(e) {
      var err = new Error('Parser is unable to parse the response');
      err.parse = true;
      err.original = e;
      self.callback(err);
    }
  });
}

/**
 * Mixin `Emitter`.
 */

Emitter(Request.prototype);

/**
 * Allow for extension
 */

Request.prototype.use = function(fn) {
  fn(this);
  return this;
}

/**
 * Set timeout to `ms`.
 *
 * @param {Number} ms
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.timeout = function(ms){
  this._timeout = ms;
  return this;
};

/**
 * Clear previous timeout.
 *
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.clearTimeout = function(){
  this._timeout = 0;
  clearTimeout(this._timer);
  return this;
};

/**
 * Abort the request, and clear potential timeout.
 *
 * @return {Request}
 * @api public
 */

Request.prototype.abort = function(){
  if (this.aborted) return;
  this.aborted = true;
  this.xhr.abort();
  this.clearTimeout();
  this.emit('abort');
  return this;
};

/**
 * Set header `field` to `val`, or multiple fields with one object.
 *
 * Examples:
 *
 *      req.get('/')
 *        .set('Accept', 'application/json')
 *        .set('X-API-Key', 'foobar')
 *        .end(callback);
 *
 *      req.get('/')
 *        .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
 *        .end(callback);
 *
 * @param {String|Object} field
 * @param {String} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.set = function(field, val){
  if (isObject(field)) {
    for (var key in field) {
      this.set(key, field[key]);
    }
    return this;
  }
  this._header[field.toLowerCase()] = val;
  this.header[field] = val;
  return this;
};

/**
 * Remove header `field`.
 *
 * Example:
 *
 *      req.get('/')
 *        .unset('User-Agent')
 *        .end(callback);
 *
 * @param {String} field
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.unset = function(field){
  delete this._header[field.toLowerCase()];
  delete this.header[field];
  return this;
};

/**
 * Get case-insensitive header `field` value.
 *
 * @param {String} field
 * @return {String}
 * @api private
 */

Request.prototype.getHeader = function(field){
  return this._header[field.toLowerCase()];
};

/**
 * Set Content-Type to `type`, mapping values from `request.types`.
 *
 * Examples:
 *
 *      superagent.types.xml = 'application/xml';
 *
 *      request.post('/')
 *        .type('xml')
 *        .send(xmlstring)
 *        .end(callback);
 *
 *      request.post('/')
 *        .type('application/xml')
 *        .send(xmlstring)
 *        .end(callback);
 *
 * @param {String} type
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.type = function(type){
  this.set('Content-Type', request.types[type] || type);
  return this;
};

/**
 * Set Accept to `type`, mapping values from `request.types`.
 *
 * Examples:
 *
 *      superagent.types.json = 'application/json';
 *
 *      request.get('/agent')
 *        .accept('json')
 *        .end(callback);
 *
 *      request.get('/agent')
 *        .accept('application/json')
 *        .end(callback);
 *
 * @param {String} accept
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.accept = function(type){
  this.set('Accept', request.types[type] || type);
  return this;
};

/**
 * Set Authorization field value with `user` and `pass`.
 *
 * @param {String} user
 * @param {String} pass
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.auth = function(user, pass){
  var str = btoa(user + ':' + pass);
  this.set('Authorization', 'Basic ' + str);
  return this;
};

/**
* Add query-string `val`.
*
* Examples:
*
*   request.get('/shoes')
*     .query('size=10')
*     .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/

Request.prototype.query = function(val){
  if ('string' != typeof val) val = serialize(val);
  if (val) this._query.push(val);
  return this;
};

/**
 * Write the field `name` and `val` for "multipart/form-data"
 * request bodies.
 *
 * ``` js
 * request.post('/upload')
 *   .field('foo', 'bar')
 *   .end(callback);
 * ```
 *
 * @param {String} name
 * @param {String|Blob|File} val
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.field = function(name, val){
  if (!this._formData) this._formData = new FormData();
  this._formData.append(name, val);
  return this;
};

/**
 * Queue the given `file` as an attachment to the specified `field`,
 * with optional `filename`.
 *
 * ``` js
 * request.post('/upload')
 *   .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
 *   .end(callback);
 * ```
 *
 * @param {String} field
 * @param {Blob|File} file
 * @param {String} filename
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.attach = function(field, file, filename){
  if (!this._formData) this._formData = new FormData();
  this._formData.append(field, file, filename);
  return this;
};

/**
 * Send `data`, defaulting the `.type()` to "json" when
 * an object is given.
 *
 * Examples:
 *
 *       // querystring
 *       request.get('/search')
 *         .end(callback)
 *
 *       // multiple data "writes"
 *       request.get('/search')
 *         .send({ search: 'query' })
 *         .send({ range: '1..5' })
 *         .send({ order: 'desc' })
 *         .end(callback)
 *
 *       // manual json
 *       request.post('/user')
 *         .type('json')
 *         .send('{"name":"tj"})
 *         .end(callback)
 *
 *       // auto json
 *       request.post('/user')
 *         .send({ name: 'tj' })
 *         .end(callback)
 *
 *       // manual x-www-form-urlencoded
 *       request.post('/user')
 *         .type('form')
 *         .send('name=tj')
 *         .end(callback)
 *
 *       // auto x-www-form-urlencoded
 *       request.post('/user')
 *         .type('form')
 *         .send({ name: 'tj' })
 *         .end(callback)
 *
 *       // defaults to x-www-form-urlencoded
  *      request.post('/user')
  *        .send('name=tobi')
  *        .send('species=ferret')
  *        .end(callback)
 *
 * @param {String|Object} data
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.send = function(data){
  var obj = isObject(data);
  var type = this.getHeader('Content-Type');

  // merge
  if (obj && isObject(this._data)) {
    for (var key in data) {
      this._data[key] = data[key];
    }
  } else if ('string' == typeof data) {
    if (!type) this.type('form');
    type = this.getHeader('Content-Type');
    if ('application/x-www-form-urlencoded' == type) {
      this._data = this._data
        ? this._data + '&' + data
        : data;
    } else {
      this._data = (this._data || '') + data;
    }
  } else {
    this._data = data;
  }

  if (!obj) return this;
  if (!type) this.type('json');
  return this;
};

/**
 * Invoke the callback with `err` and `res`
 * and handle arity check.
 *
 * @param {Error} err
 * @param {Response} res
 * @api private
 */

Request.prototype.callback = function(err, res){
  var fn = this._callback;
  if (2 == fn.length) return fn(err, res);
  if (err) return this.emit('error', err);
  fn(res);
};

/**
 * Invoke callback with x-domain error.
 *
 * @api private
 */

Request.prototype.crossDomainError = function(){
  var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
  err.crossDomain = true;
  this.callback(err);
};

/**
 * Invoke callback with timeout error.
 *
 * @api private
 */

Request.prototype.timeoutError = function(){
  var timeout = this._timeout;
  var err = new Error('timeout of ' + timeout + 'ms exceeded');
  err.timeout = timeout;
  this.callback(err);
};

/**
 * Enable transmission of cookies with x-domain requests.
 *
 * Note that for this to work the origin must not be
 * using "Access-Control-Allow-Origin" with a wildcard,
 * and also must set "Access-Control-Allow-Credentials"
 * to "true".
 *
 * @api public
 */

Request.prototype.withCredentials = function(){
  this._withCredentials = true;
  return this;
};

/**
 * Initiate request, invoking callback `fn(res)`
 * with an instanceof `Response`.
 *
 * @param {Function} fn
 * @return {Request} for chaining
 * @api public
 */

Request.prototype.end = function(fn){
  var self = this;
  var xhr = this.xhr = getXHR();
  var query = this._query.join('&');
  var timeout = this._timeout;
  var data = this._formData || this._data;

  // store callback
  this._callback = fn || noop;

  // state change
  xhr.onreadystatechange = function(){
    if (4 != xhr.readyState) return;
    if (0 == xhr.status) {
      if (self.aborted) return self.timeoutError();
      return self.crossDomainError();
    }
    self.emit('end');
  };

  // progress
  if (xhr.upload) {
    xhr.upload.onprogress = function(e){
      e.percent = e.loaded / e.total * 100;
      self.emit('progress', e);
    };
  }

  // timeout
  if (timeout && !this._timer) {
    this._timer = setTimeout(function(){
      self.abort();
    }, timeout);
  }

  // querystring
  if (query) {
    query = request.serializeObject(query);
    this.url += ~this.url.indexOf('?')
      ? '&' + query
      : '?' + query;
  }

  // initiate request
  xhr.open(this.method, this.url, true);

  // CORS
  if (this._withCredentials) xhr.withCredentials = true;

  // body
  if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
    // serialize stuff
    var serialize = request.serialize[this.getHeader('Content-Type')];
    if (serialize) data = serialize(data);
  }

  // set header fields
  for (var field in this.header) {
    if (null == this.header[field]) continue;
    xhr.setRequestHeader(field, this.header[field]);
  }

  // send stuff
  this.emit('request', this);
  xhr.send(data);
  return this;
};

/**
 * Expose `Request`.
 */

request.Request = Request;

/**
 * Issue a request:
 *
 * Examples:
 *
 *    request('GET', '/users').end(callback)
 *    request('/users').end(callback)
 *    request('/users', callback)
 *
 * @param {String} method
 * @param {String|Function} url or callback
 * @return {Request}
 * @api public
 */

function request(method, url) {
  // callback
  if ('function' == typeof url) {
    return new Request('GET', method).end(url);
  }

  // url first
  if (1 == arguments.length) {
    return new Request('GET', method);
  }

  return new Request(method, url);
}

/**
 * GET `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed|Function} data or fn
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.get = function(url, data, fn){
  var req = request('GET', url);
  if ('function' == typeof data) fn = data, data = null;
  if (data) req.query(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * HEAD `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed|Function} data or fn
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.head = function(url, data, fn){
  var req = request('HEAD', url);
  if ('function' == typeof data) fn = data, data = null;
  if (data) req.send(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * DELETE `url` with optional callback `fn(res)`.
 *
 * @param {String} url
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.del = function(url, fn){
  var req = request('DELETE', url);
  if (fn) req.end(fn);
  return req;
};

/**
 * PATCH `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.patch = function(url, data, fn){
  var req = request('PATCH', url);
  if ('function' == typeof data) fn = data, data = null;
  if (data) req.send(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * POST `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed} data
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.post = function(url, data, fn){
  var req = request('POST', url);
  if ('function' == typeof data) fn = data, data = null;
  if (data) req.send(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * PUT `url` with optional `data` and callback `fn(res)`.
 *
 * @param {String} url
 * @param {Mixed|Function} data or fn
 * @param {Function} fn
 * @return {Request}
 * @api public
 */

request.put = function(url, data, fn){
  var req = request('PUT', url);
  if ('function' == typeof data) fn = data, data = null;
  if (data) req.send(data);
  if (fn) req.end(fn);
  return req;
};

/**
 * Expose `request`.
 */

module.exports = request;

},{"emitter":2,"reduce":3}],2:[function(require,module,exports){
示例#30
0
},{}],23:[function(require,module,exports){
function noop(){}function isHost(t){var e={}.toString.call(t);switch(e){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}}function isObject(t){return t===Object(t)}function serialize(t){if(!isObject(t))return t;var e=[];for(var r in t)null!=t[r]&&e.push(encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e.join("&")}function parseString(t){for(var e,r,s={},i=t.split("&"),o=0,n=i.length;n>o;++o)r=i[o],e=r.split("="),s[decodeURIComponent(e[0])]=decodeURIComponent(e[1]);return s}function parseHeader(t){var e,r,s,i,o=t.split(/\r?\n/),n={};o.pop();for(var a=0,u=o.length;u>a;++a)r=o[a],e=r.indexOf(":"),s=r.slice(0,e).toLowerCase(),i=trim(r.slice(e+1)),n[s]=i;return n}function type(t){return t.split(/ *; */).shift()}function params(t){return reduce(t.split(/ *; */),function(t,e){var r=e.split(/ *= */),s=r.shift(),i=r.shift();return s&&i&&(t[s]=i),t},{})}function Response(t,e){e=e||{},this.req=t,this.xhr=this.req.xhr,this.text="HEAD"!=this.req.method&&(""===this.xhr.responseType||"text"===this.xhr.responseType)||"undefined"==typeof this.xhr.responseType?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText,this.setStatusProperties(this.xhr.status),this.header=this.headers=parseHeader(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this.setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this.parseBody(this.text?this.text:this.xhr.response):null}function Request(t,e){var r=this;Emitter.call(this),this._query=this._query||[],this.method=t,this.url=e,this.header={},this._header={},this.on("end",function(){var t=null,e=null;try{e=new Response(r)}catch(s){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=s,r.callback(t)}if(r.emit("response",e),t)return r.callback(t,e);if(e.status>=200&&e.status<300)return r.callback(t,e);var i=new Error(e.statusText||"Unsuccessful HTTP response");i.original=t,i.response=e,i.status=e.status,r.callback(t||i,e)})}function request(t,e){return"function"==typeof e?new Request("GET",t).end(e):1==arguments.length?new Request("GET",t):new Request(t,e)}var Emitter=require("emitter"),reduce=require("reduce"),root="undefined"==typeof window?this||self:window;request.getXHR=function(){if(!(!root.XMLHttpRequest||root.location&&"file:"==root.location.protocol&&root.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}return!1};var trim="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};request.serializeObject=serialize,request.parseString=parseString,request.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},request.serialize={"application/x-www-form-urlencoded":serialize,"application/json":JSON.stringify},request.parse={"application/x-www-form-urlencoded":parseString,"application/json":JSON.parse},Response.prototype.get=function(t){return this.header[t.toLowerCase()]},Response.prototype.setHeaderProperties=function(t){var e=this.header["content-type"]||"";this.type=type(e);var r=params(e);for(var s in r)this[s]=r[s]},Response.prototype.parseBody=function(t){var e=request.parse[this.type];return e&&t&&(t.length||t instanceof Object)?e(t):null},Response.prototype.setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=4==e||5==e?this.toError():!1,this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},Response.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,s="cannot "+e+" "+r+" ("+this.status+")",i=new Error(s);return i.status=this.status,i.method=e,i.url=r,i},request.Response=Response,Emitter(Request.prototype),Request.prototype.use=function(t){return t(this),this},Request.prototype.timeout=function(t){return this._timeout=t,this},Request.prototype.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},Request.prototype.abort=function(){return this.aborted?void 0:(this.aborted=!0,this.xhr.abort(),this.clearTimeout(),this.emit("abort"),this)},Request.prototype.set=function(t,e){if(isObject(t)){for(var r in t)this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},Request.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},Request.prototype.getHeader=function(t){return this._header[t.toLowerCase()]},Request.prototype.type=function(t){return this.set("Content-Type",request.types[t]||t),this},Request.prototype.accept=function(t){return this.set("Accept",request.types[t]||t),this},Request.prototype.auth=function(t,e){var r=btoa(t+":"+e);return this.set("Authorization","Basic "+r),this},Request.prototype.query=function(t){return"string"!=typeof t&&(t=serialize(t)),t&&this._query.push(t),this},Request.prototype.field=function(t,e){return this._formData||(this._formData=new root.FormData),this._formData.append(t,e),this},Request.prototype.attach=function(t,e,r){return this._formData||(this._formData=new root.FormData),this._formData.append(t,e,r),this},Request.prototype.send=function(t){var e=isObject(t),r=this.getHeader("Content-Type");if(e&&isObject(this._data))for(var s in t)this._data[s]=t[s];else"string"==typeof t?(r||this.type("form"),r=this.getHeader("Content-Type"),"application/x-www-form-urlencoded"==r?this._data=this._data?this._data+"&"+t:t:this._data=(this._data||"")+t):this._data=t;return!e||isHost(t)?this:(r||this.type("json"),this)},Request.prototype.callback=function(t,e){var r=this._callback;this.clearTimeout(),r(t,e)},Request.prototype.crossDomainError=function(){var t=new Error("Origin is not allowed by Access-Control-Allow-Origin");t.crossDomain=!0,this.callback(t)},Request.prototype.timeoutError=function(){var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},Request.prototype.withCredentials=function(){return this._withCredentials=!0,this},Request.prototype.end=function(t){var e=this,r=this.xhr=request.getXHR(),s=this._query.join("&"),i=this._timeout,o=this._formData||this._data;this._callback=t||noop,r.onreadystatechange=function(){if(4==r.readyState){var t;try{t=r.status}catch(s){t=0}if(0==t){if(e.timedout)return e.timeoutError();if(e.aborted)return;return e.crossDomainError()}e.emit("end")}};var n=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),e.emit("progress",t)};this.hasListeners("progress")&&(r.onprogress=n);try{r.upload&&this.hasListeners("progress")&&(r.upload.onprogress=n)}catch(a){}if(i&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},i)),s&&(s=request.serializeObject(s),this.url+=~this.url.indexOf("?")?"&"+s:"?"+s),r.open(this.method,this.url,!0),this._withCredentials&&(r.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof o&&!isHost(o)){var u=request.serialize[this.getHeader("Content-Type")];u&&(o=u(o))}for(var h in this.header)null!=this.header[h]&&r.setRequestHeader(h,this.header[h]);return this.emit("request",this),r.send(o),this},request.Request=Request,request.get=function(t,e,r){var s=request("GET",t);return"function"==typeof e&&(r=e,e=null),e&&s.query(e),r&&s.end(r),s},request.head=function(t,e,r){var s=request("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&s.send(e),r&&s.end(r),s},request.del=function(t,e){var r=request("DELETE",t);return e&&r.end(e),r},request.patch=function(t,e,r){var s=request("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&s.send(e),r&&s.end(r),s},request.post=function(t,e,r){var s=request("POST",t);return"function"==typeof e&&(r=e,e=null),e&&s.send(e),r&&s.end(r),s},request.put=function(t,e,r){var s=request("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&s.send(e),r&&s.end(r),s},module.exports=request;

},{"emitter":5,"reduce":22}],24:[function(require,module,exports){