working on it ...

Filters

Explore Public Snippets

Sort by

Found 28k snippets matching: event

    public by sTiLL-iLL @ SniPitz-KND  532543  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL @ SniPitz-KND  444538  3  8  24

    Signals.js... A fast and efficient event system in javascript.

    Signals.js... A fast and efficient event system in javascript.: Signals.js
    // Signalz.js
    
    var Signals = (function () {
    	'use strict';
    	var sigCache = {},
    	addReceiver = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	signalReceived = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	dropReceivers = function (eventName) {
    		if (!eventName) {
    			sigCache = {};
    			return this;
    		}
    		if (sigCache && sigCache[eventName]) {
    			sigCache[eventName] = null;
    		}
    		return this;
    	},    
    	signalOnce = function (eventName, func) {
    		var slf = this;
    		setSingleRV(true);
    		function onit () {
    			dropReceiver(eventName, wen);
    			func.apply(this, arguments);
    		};
    		wen.receiver = onit;	
    		return this;
    	},
    	dropReceiver = function (eventName, func) {
    		if (sigCache && sigCache[eventName]) {
    			var sigLst = sigCache[eventName];	
    			if (isAry(sigLst)) {
    				var idx = -1;
    				for (var i = 0, l = sigLst.length; i < l; i++) {
    					if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
    						idx = i;
    						break;
    					}
    				}
    				if (idx < 0) {
    					return this;
    				}
    				sigLst.splice(idx, 1);
    				if (!sigLst.length) {
    					delete sigCache[eventName];
    				}
    			} 
    			else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
    				delete sigCache[eventName];
    			}
    		}
    		return this;
    	},  
    	setSingleRV = function (val) {
    		singleRtnVal = val;
    		return this;
    	},  
    	getSingleRV = function() {
    		if (receivers.hasOwnProperty('singleRtnVal')) {
    			return singleRtnVal;
    		}
    		else {
    			return true;
    		}
    	},	 
    	castSignal = function(eventName, args) {
    		var recvrLst = receiverObjects(eventName),
    		k, recvr, i, rspns;
    		for (k in recvrLst ) {
    			if (recvrLst.hasOwnProperty(k)) {
    				i = recvrLst[k].length;		
    				while (i--) {
    					recvr = recvrLst[k][i];
    					if (recvr.signalOnce === true) {
    						dropReceiver(eventName, recvr);
    					}	
    					rspns = recvr.call(this, args || []);
    					if (rspns === getSingleRV()) {
    						dropReceiver(eventName, recvr);
    					}
    				}
    			}
    		}
    	 	return this;
      	};
    	function isAry(obj) {
    		return (obj.constructor === Array);
    	};
    	function receiverObjects(eventName) {
    		var recvrLst = receivers(eventName), rspns;	
    		if (isAry(recvrLst)) {
    			rspns = {};
    			rspns[eventName] = recvrLst;
    		}	
    		return rspns || recvrLst;
    	};
    	function receivers(eventName) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = [];
    		}
    		if (!isAry(sigCache[eventName])) {
    			sigCache[eventName] = [sigCache[eventName]];
    		}
    		return sigCache[eventName];
    	};
    	function wen(eventName, func) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = func;
    		} 
    		else if (isArry(sigCache[eventName])) {
    			sigCache[eventName].push(func);
    		} 
    		else {
    			sigCache[eventName] = [sigCache[eventName], func];
    		}	
    		return;
    	};
    	return {
    		signal: castSignal,
    		signaled: signalReceived,
    		receive: addReceiver,
    		receiveOnce: signalOnce,
    		signaledOnce: signalOnce,
    		dropReceiver: dropReceiver,
    		assignReceiver: addReceiver,
    		receivers: receivers,
    		dropReceivers: dropReceivers
    	};
    }());
    
    exports.Signals = Signals;
    
    
                

    public by micurs  267835  11  7  2

    Check if Event was Triggered or Native

    You can easily add extra argument when triggering an event function programmatically in jquery. This way you can recognize if the event was triggered by a real mouse click rather than a direct call to the .click() function. As seen on http://css-tricks.com/snippets/jquery/check-if-event-was-triggered-or-native/
    $('button').click(function(event, wasTriggered) {
        if (wasTriggered) {
            alert('triggered in code');
        } else {
            alert('triggered by mouse');
        }
    });
    
    $('button').trigger('click', true);

    public by HeathDernovich  262015  0  4  1

    An example of inheriting from event emitter

    An example of inheriting from event emitter: EventEmitterPattern.js
    // Require our emitter
    
    var Emitter = require('events').EventEmitter;
    
    // Our main constructor
    
    var myEmitter = function (config) {
      // extend with emitter
      Emitter.call(this);
      };
      // Inherit from emitter, but keep my constructor
      
      myEmitter.prototype = Object.create(Emitter.prototype, {
        constructor: {
          value: myEmitter
        }
      });
      
      // methods
      
    myEmitter.prototype.setName = function (nam) {
      this.name = nam;
      this.emit('nameChanged', name);
     };
     
    module.exports = myEmitter;
    
    

    public by sTiLL-iLL  195534  6  9  23

    Watchable.js ie. observable & chainable

    eventing wrapper for objects and nodes
    
    // uses browser(ed) version of event-emitter as a dependancy
    
    var events = EventEmitter;
     
    function watchable(obj) {
    	
    	var that = this;
    	var first = true;
    	var x = null;
    	var ob = obj || undefined;
    
    	if(first) { 	
    		events.call(this);
    		x = obj || null;
    		first = false;
    		return this;
    	 } 
    	 else {
    		if(!ob) {
    			return x;
    		} 
    		else {
    			x = ob;
    			ob = undefined;
    			this.emit("change", x);
    		}
             	 }
    };
    
    watchable.prototype = Object.create(events.prototype, {
        			constructor: {
          				value: watchable
       			}
      		});
    
    watchable.prototype.val = function(v) {
    			if(!v) { 
    				return x;
    			}
    			x = v;
      			this.emit('change', x);
    			return this;
      		};
    
    watchable.prototype.fire = function(str, obj) {
      			this.emit(str, obj);
    			return this;
      		};
    
    watchable.prototype.when = function(str, fnc) {
      			this.on(str, function(ev) {
    					fnc(ev);
    				});
    			return this;
      		};
    
    watchable.prototype.change = function() {
      			this.emit('change', x);
    			return this;
      		};
    

    public by sTiLL-iLL @ SniPitz-KND  183869  1  8  23

    EventDelagateAsyncContextMessageBuzzWordObject

    does it work? IDK... havent tried.. the idea is solid... itll prolly work... without to much effort...
    // polyfill first... just in case
    
    if(!window.CustomEvent) {
      (function(wdw) {
        function CustomEvent ( event, params ) {
          params = params || { bubbles: false, cancelable: false, detail: undefined };
          var evt = document.createEvent( 'CustomEvent' );
          evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
          return evt;
        }
        CustomEvent.prototype = window.Event.prototype;
        wdw.CustomEvent = CustomEvent;
      }(window));
    }
    
    function ContextConnection_ChannelBroker(document) {
    	var slf = this;
    	this.create = function (evtName, obj) {
    	  var eventChannel = new CustomEvent(eventName, 
    	    {
    	      bubbles: true,
    	      cancelable: true,
    	      detail: obj
    	     });
    	     
    	  this.fwdResult = function (rslt) {
    			obj.dispatchEvent(evtName, rslt);
    		};
    		
    		this.objPxy = (function(fwdResult) {
    			this.eventChannel.call(slf);
    			obj.addEventListener(evtName, function (ev) {
    				ev.preventDefault();
    				return obj.bind(fwdResult(ev));
    			});
    			return obj;
    		}());
    		
    		return objPxy;
    	};
    	
    	objPxy.prototype = Object.create(obj.prototype,	{ 
    	  constructor: {
    	    value: objPxy,
    	    enumerable: false
    	  }
    	});
    	objPxy.prototype.on = function (n,fnc) {
    		obj.addEventListener(n, function(e) {
    			fnc(e.data);
    		});
    	};
    	objPxy.prototype.emit = function (n,obj) {
    		obj.dispatchEvent(n, obj);
    	};	
    	return {
    		onSignaled: on,
    		emitSignal:	emit,
    		createContextChannel: create
    	}
    };

    public by cghersi  204451  0  6  2

    Embed a browser into SWT Dialog and manage the firing of popups from links in the displayed page

    This is how to manage an embedded browser. Note: unfortunately this seems not working on some versions of Mac OS X.
    try {
    	Browser browser = new Browser(this, SWT.NONE);
    	browser.setJavascriptEnabled(true);
    	browser.setUrl("www.myurl.com");
    	browser.addOpenWindowListener(new OpenWindowListener() {
    		public void open(WindowEvent event) {
    			log.debug("Opening browser:" + event);
    			new Thread( new Runnable() {
    	            public void run() {
    	            	log.debug("some stuff t do here...");
    	            }
    			}).start();
    			
    			final Shell shell = new Shell(event.display);
    		    shell.setText("My Browser page");
    		    shell.setLayout(new FillLayout());
    		    event.browser = new Browser(shell, SWT.NONE);
    		    shell.open();
    		    
    		    event.browser.addCloseWindowListener(new CloseWindowListener() {
    				@Override
    				public void close(WindowEvent event) {
    					log.debug("closing");
    					shell.setVisible(false);
    				}
    			});
    		}
    	});
    } catch (Throwable t) {
    	//on some architecture seems that SWT Browser is not working...
    	log.warn("Cannot display SWT Browser");
    }

    public by lbottaro  89603  665  8  8

    How to collapse a div in html

    This code shows how to collapse a div using a simple Javascript method. The div display option toggles between 'none' and 'block', hiding or showing its content. In the example you can collapse the div clicking both on a link or on a div, using the onclick event.
    <!doctype html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>Test</title>
    		<script language="javascript"> 
    function toggle(elementId) {
    	var ele = document.getElementById(elementId);
    	if(ele.style.display == "block") {
        		ele.style.display = "none";
      	}
    	else {
    		ele.style.display = "block";
    	}
    } 
    </script>
    	</head>
    	<body>
    <div class="tree">
    <div>
    BLA BLA
    </div>	
    <a id="displayText" href="javascript:toggle('toggleText');">show</a> <== click Here
    <div onclick="javascript:toggle('toggleText');">
    <h1>Hello!</h1>
    <div id="toggleText" style="display:none; border-width:2px; border-style:solid">Hidden data...</div>
    </div>
    <div>
    BLA
    </div>	
    <div>
    BLA BLA 
    </div>	
    <div>
    BLA BLA 123
    </div>
    <a id="displayText" href="javascript:toggle('toggleText2');">show</a> <== click Here
    <div id="toggleText2" style="display: none" href="javascript:toggle();"><h1>Hide!</h1></div>	
    </div></body>
    </html>

    public by David Grayson  145029  2  3  0

    Simple Windows C program that connects to a serial port and prints out events from it, such as ring signals.

    Simple Windows C program that connects to a serial port and prints out events from it, such as ring signals.: serial.c
    // Lots of code was copied from https://msdn.microsoft.com/en-us/library/ff802693.aspx#serial_topic3
    
    #include <assert.h>
    #include <windows.h>
    #include <stdio.h>
    #include <stdbool.h>
    
    void ReportStatusEvent(DWORD s)
    {
        if (s == EV_RING)
        {
            printf("ring\n");
        }
        else
        {
            printf("status = 0x%lx\n", s);
        }
    }
    
    int main(int argc, char ** argv)
    {
        if (argc < 2)
        {
            fprintf(stderr, "Need at least one argument to specify the COM port.\n");
            return 1;
        }
    
        HANDLE port = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE,
            0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
        if (port == INVALID_HANDLE_VALUE)
        {
            DWORD error = GetLastError();
            fprintf(stderr, "Could not open port.  Error 0x%lx.\n", error);
            return 1;
        }
    
        DWORD flags = EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING |
            EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY;
        BOOL success = SetCommMask(port, flags);
        if (!success)
        {
            fprintf(stderr, "Could not set comm mask.\n");
        }
    
        OVERLAPPED osStatus = {0};
        osStatus.hEvent = CreateEvent(NULL, true, false, NULL);
        assert(osStatus.hEvent);
    
        DWORD dwCommEvent;
        BOOL fWaitingOnStat = FALSE;
        while (true)
        {
            // Issue a status event check if one hasn't been issued already.
            if (!fWaitingOnStat)
            {
                //fprintf(stderr, "Calling WaitCommEvent\n");
                if (!WaitCommEvent(port, &dwCommEvent, &osStatus))
                {
                    if (GetLastError() == ERROR_IO_PENDING)
                    {
                        fWaitingOnStat = TRUE;
                        //fprintf(stderr, "WaitCommEvent result is ERROR_IO_PENDING\n");
                    }
                    else
                    {
                        fprintf(stderr, "Error in WaitCommEvent\n");
                        break; // abort
                    }
                }
                else
                {
                    // WaitCommEvent returned immediately.
                    // Deal with status event as appropriate.
                    ReportStatusEvent(dwCommEvent);
                }
            }
    
            // Check on overlapped operation.
            if (fWaitingOnStat)
            {
                DWORD dwOvRes;
    
                // Wait a little while for an event to occur.
                //fprintf(stderr, "Calling WaitForSingleObject\n");
                DWORD dwRes = WaitForSingleObject(osStatus.hEvent, 100);
                switch(dwRes)
                {
                case WAIT_OBJECT_0:
                    // Event occurred.
                    if (!GetOverlappedResult(port, &osStatus, &dwOvRes, FALSE))
                    {
                        // An error occurred in the overlapped operation;
                        // call GetLastError to find out what it was
                        // and abort if it is fatal.
                        fprintf(stderr, "Error from GetOverlappedResult\n");
                    }
                    else
                    {
                        // Status event is stored in the event flag
                        // specified in the original WaitCommEvent call.
                        // Deal with the status event as appropriate.
                        ReportStatusEvent(dwCommEvent);
                    }
    
                    // Set fWaitingOnStat flag to indicate that a new
                    // WaitCommEvent is to be issued.
                    fWaitingOnStat = FALSE;
                    break;
    
                case WAIT_TIMEOUT:
                    // Operation isn't complete yet. fWaitingOnStatusHandle flag
                    // isn't changed since I'll loop back around and I don't want
                    // to issue another WaitCommEvent until the first one finishes.
                    //
                    // This is a good time to do some background work.
                    //fprintf(stderr, "WAIT_TIMEOUT\n");
                    break;
    
                default:
                    // Error in the WaitForSingleObject; abort
                    // This indicates a problem with the OVERLAPPED structure's
                    // event handle.
                    fprintf(stderr, "Error in WaitForSingleObject\n");
                    CloseHandle(osStatus.hEvent);
                    return 70;
                }
            }
        }
    
        return 0;
    }
    
    
    

    public by zer00ne  2664  4  5  0

    Single Event Handler for Multiple Elements

    addEventListener to an ancestor element of multiple descendant elements
    /*
    HTML should comprise of a group of elements intended 
    to be clicked or any other event trigged by user interaction.
    The parentSelector parameter is any working selector to
    reference an element that is an ancestor to that group of
    elements.
    EX.
    <section id="perentEle">
      <a href="#" id='link1'>Link 1</a>
      <a href="#" id='link2'>Link 2</a>
      <a href="#" id='link3'>Link 3</a>
    </section>
    */
    var parentEle = document.querySelector(parentSelector);
    
    parentEle.addEventListener('click', testFunc, false);
    
    function testFunc(event) {
      event.preventDefault();
      if(event.target !== target.currentTarget) {
        var clickedChild = event.target.id;
        var child = document.getElementById(clickedChild);
        alert('ID: ' + child.id);
      }
      event.stopPropagation();
    }
    • Public Snippets
    • Channels Snippets