working on it ...

Filters

Explore Public Snippets

Sort by

Found 126k snippets matching: javascript

    public by micurs modified Mar 4, 2014  6862964  301  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  531889  2  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 lbottaro modified Dec 10, 2014  475630  5  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by sTiLL-iLL @ SniPitz-KND modified Dec 15, 2014  443968  2  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 zenitramPRO modified May 4, 2016  404138  3  5  1

    Adding an Element in an Array using a Function.

    Arrays of Objects Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects. Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Person objects, similar
    // Our person constructor
    function Person (name, age) {
        this.name = name;
        this.age = age;
    }
    
    // Now we can make an array of people
    var family = new Array();
    family[0] = new Person("alice", 40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle", 8);
    // add the last family member, "timmy", who is 6 years old
    family[3] = new Person("timmy", 6);
                                                    

    public by sTiLL-iLL @ SniPitz-KND modified Nov 10, 2014  378066  6  9  29

    set.js... its my "Set", it runs this code-block

    Full on structure type implimentation of a Set
    
    // Set....   hut-1, hut-2, hike!
    
    function Set() {
       this.dStr = [];
       this.size = size;
       this.unionOf = unionOf;
       this.contains = contains;
       this.subSet = subSet;
       this.getDiff = getDiff;
       this.removeItem = removeItem;
       this.intersection = intersection;
       this.addItem = addItem;
       this.show = show;
    }
    
    function show() {
       return "[" + this.dStr + "]";
    }
    
    function size() {
       return this.dStr.length;
    }
    
    
    
    function addItem(dta) {
       if (this.dStr.indexOf(dta) < 0) {
          this.dStr.push(dta);
          return true;
       } 
       else {
          return false;
       }
    }
    
    function removeItem(dta) {
       var pstn = this.dStr.indexOf(dta);
       if (pstn > -1) {
          this.dStr.splice(pstn, 1);
          return true;
       }
       else {
          return false;
       }
    }
    
    function contains(dta) {
       if (this.dStr.indexOf(dta) > -1) {
          return true;
       }
       else {
          return false;
       }
    }
    
    function unionOf(set) {
       var tmp = new Set(),
           i = 0;
       for (;i < this.dStr.length; ++i) {
          tmp.add(this.dStr[i]);
       }
       i = 0;
       for (;i < set.dStr.length; ++i) {
          if (!tmp.contains(set.dStr[i])) {
             tmp.dStr.push(set.dStr[i]);
          }
       }
       return tmp;
    }
    
    function intersection(set) {
       var tSet = new Set();
       for (var i = 0; i < this.dStr.length; ++i) {
          if (set.contains(this.dStr[i])) {
             tSet.add(this.dStr[i]);
          }
       }
       return tmp;
    }
    
    function subSet(set) {
       if (this.size() > set.size()) {
          return false;
       }
       else {
          for each (var m in this.dStr) {
             if (!set.contains(m)) {
                return false;
             }
          }
       }
       return true;
    }
    i = 0;
    function difference(set) {
       var tmp = new Set();
       for (;i < this.dStor.length; ++i) {
          if (!set.contains(this.dStor[i])) {
             tmp.add(this.dStor[i]);
          }
       }
       return tmp;
    }  
    
    
    

    public by pan modified Jan 17, 2015  312439  0  7  4

    CSS Regex Selector Extension For jQuery

    Using this extension enables regular expresions css selectors in jQuery
    /**
     * CSS Regex Selector Extension For jQuery
     * 
     */
    jQuery.expr[':'].regex = function(elem, index, match) {
       var matchParams = match[3].split(','),
           validLabels = /^(data|css):/,
           attr = {
               method: matchParams[0].match(validLabels) ?
                   matchParams[0].split(':')[0] : 'attr',
               property: matchParams.shift().replace(validLabels,'')
           },
           regexFlags = 'ig',
           regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
       return regex.test(jQuery(elem)[attr.method](attr.property));
    }

    public by alaindresse modified Feb 22, 2013  370568  3  6  0

    Gist to demonstrate ajax request on checkbox

    Gist to demonstrate ajax request on checkbox: ajax-checkbox.tag ajaxCheckbox.java main.js view.jsp
    // Tagfile to be placed in WEB-INF/tags/ui
    
    <%@tag import="com.liferay.portal.kernel.util.HtmlUtil"%>
    <%@tag import="com.liferay.portal.kernel.language.LanguageUtil"%>
    <%@tag import="com.liferay.portal.kernel.util.StringPool"%>
    <%@tag import="com.liferay.portal.util.PortalUtil"%>
    <%@ attribute 
    	name="resourceUrl"
    	description="URL to process the ajax call. ServeResource parameter: newValue (0 or 1 for unchecked, checked). responseData is not used. An alert is open on failure."
    	type="String" 
    	required="true" %>
    <%@ attribute
    	name="name"
    	description="Checkbox name. A random name is set if this is not provided."
    	type="String"%>
    <%@ attribute
    	name="label"
    	description="Checkbox label"
    	type="String"
    	required="true" %>
    <%@ attribute
    	name="initialValue"
    	description="Initial value of checkbox"
    	type="Boolean"
    	required="true" %>
    <%@ attribute
    	name="successCallback"
    	description="ajax callback on success. Parameters are: checkbox node, response data."
    	type="String" %>
    <%@ attribute
    	name="failureCallback"
    	description="Callback on failure. Parameter is checkbox name."
    	type="String" %>
    	
    <%@ taglib uri="http://liferay.com/tld/theme" prefix="theme" %>
    <%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
    <%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
    <portlet:defineObjects />
    <theme:defineObjects />
    
    <%
    if (name == null){
    	name = PortalUtil.generateRandomKey(request, "ajaxToggleKey");
    }
    String onclick = "bb_ajaxCheckbox('" + resourceUrl  + "', this, " + successCallback + "," + failureCallback + ")";
    %>
    <aui:input type="checkbox" onClick="<%=onclick%>" value="<%=initialValue%>" name="<%=name%>" label="<%=label%>" /> 
    
    
    	@Override
    	public void serveResource(ResourceRequest resourceRequest,
    			ResourceResponse resourceResponse) throws IOException,
    			PortletException {
    		
    		_log.info("processing resource");
    		Map<String, String[]> parameters = resourceRequest.getParameterMap();
    		for (String key : parameters.keySet()){
    			_log.info(key + ":[" + StringUtil.merge(parameters.get(key)) + "]");
    		}
    
    
    		String resourceId = resourceRequest.getResourceID();
    		if (Validator.isNotNull(resourceId)) {
    			String cmd = resourceRequest.getResourceID();
    			if (cmd.equals("testToggle")) {
    				try {
    					boolean newValue = ParamUtil.getBoolean(resourceRequest,"newValue");
    					_log.info(String.valueOf(newValue));
    					if (!newValue){
    						throw new IOException("simulate failure");
    					} else {
    						resourceResponse.setContentType("text/plain");
    						resourceResponse.getWriter().write("this is the response data");
    					}
    				} catch(Exception e){
    					throw new IOException(e);
    				}
    			}
    		}
    		super.serveResource(resourceRequest, resourceResponse);
    	}
    
    
    Liferay.provide(
    	window, 
    	"bb_ajaxCheckbox",
    	function(resourceUrl, checkbox, success, failure){
    		var A = AUI();
    		var checked = false;
    		var checkbox = A.one(checkbox);
    		var label = null;
    		if (checkbox) {
    			checked = checkbox.attr('checked');
    			var labelSelector = 'label[for="' + checkbox.attr("name") + '"]';
    			if (labelSelector) label = A.one(labelSelector);
    		}
    		var ajaxCallbacks = {
    			success: function(){
    				if (label) label.removeClass("ajax-loading");
    				if (success) success(checkbox, this.get('responseData'));
    			},
    			failure: function(){
    				if (failure) failure(checkbox);
    			}
    		};
    		if (label) label.addClass("ajax-loading");
    		A.io.request(resourceUrl, {
    			method: 'GET',
    			data: {newValue: checked,},
    			on : ajaxCallbacks,
    		});
    	}, [ 'aui-io-request' ]
    );
    
    <%@ taglib tagdir="/WEB-INF/tags/ui" prefix="bamboost-ui"%>
    <%@ include file="/html/init.jsp"%>
    
    <portlet:resourceURL id="testToggle" var="testToggleURl"/>
    <bamboost-ui:ajax-checkbox
    	name="myname" 
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="no callback"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testSuccess"
    	successCallback="testSuccess"/>
    <bamboost-ui:ajax-checkbox
    	resourceUrl="<%=testToggleURl %>" 
    	initialValue="true"
    	label="testFailure"
    	failureCallback="testFailure"/>
    	
    	<script>
    	function testSuccess(checkbox, responseData) {
    		alert(checkbox.attr("name") + "\n" + responseData);
    	};
    	function testFailure() {alert("failure");};
    	</script>
    
    

    public by f8lrebel modified Apr 24, 2013  365673  3  4  0

    Original project here: http://designitcodeit.com/i/11

    Original project here: http://designitcodeit.com/i/11: index.html script.js style.css
    CSS
    <ul class="comments">
      <li class="comment">
        <a href="#" title="View this user profile" class="photo"><img src="http://designitcodeit.com/live/45S6P0fit0nM/img/photo1.png" alt="Kasper"></a>
        <div class="meta">Kasper | 2012.07.24 14:58 <a class="reply">Reply</a></div>
        <div class="body">Cupcake ipsum dolor sit amet. Icing donut cheesecake muffin marzipan chocolate biscuit. Sweet roll chocolate marzipan.</div>
      </li>
      <li class="comment level-2">
        <a href="#" title="View this user profile" class="photo"><img src="http://designitcodeit.com/live/45S6P0fit0nM/img/photo-default.png" alt="Photo"></a>
        <div class="meta">John | 2012.07.24 15:21 <a class="reply">Reply</a></div>
        <div class="body">Candy soufflé bear claw apple pie bear claw marshmallow. Jelly brownie wafer chocolate jelly.marzipan pastry sesame snaps apple pie.</div>
      </li>
      <li class="comment level-3">
        <a href="#" title="View this user profile" class="photo"><img src="http://designitcodeit.com/live/45S6P0fit0nM/img/photo-default.png" alt="Photo"></a>
        <div class="meta">Jane | 2012.07.24 15:32 <a class="reply">Reply</a></div>
        <div class="body">Tart apple pie bonbon applicake sesame snaps sugar plum.</div>
      </li>
      <li class="comment level-4">
        <a href="#" title="View this user profile" class="photo"><img src="http://designitcodeit.com/live/45S6P0fit0nM/img/photo-default.png" alt="Photo"></a>
        <div class="meta">Jane | 2012.07.24 15:32 <a class="reply">Reply</a></div>
        <div class="body">Tart apple pie bonbon applicake sesame snaps sugar plum.</div>
      </li>
      <li class="comment">
        <a href="#" title="View this user profile" class="photo"><img src="http://designitcodeit.com/live/45S6P0fit0nM/img/photo1.png" alt="Kasper"></a>
        <div class="meta">Kasper | 2012.07.24 14:58 <a class="reply">Reply</a></div>
        <div class="body">Cupcake ipsum dolor sit amet. Icing donut cheesecake muffin marzipan chocolate biscuit.</div>
      </li>
    </ul>
    
    /* 
     * Comments thread for Design it & Code it
     * http://designitcodeit.com/i/11
     */
    
    html {
      background: #fff url(http://designitcodeit.com/live/45S6P0fit0nM/img/bg.png);
      font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
    }
    body {
      max-width: 480px;
      width: 100%;
      margin: 30px auto 0 auto;
    }
    a { cursor: pointer; }
    
    /**
     * Customs
     */
    .comments:after { border-color: #fff; }
    .comments:before { background-color: #fff; }
    .comments .comment {
      background: #fff;
      border-radius: 10px;
      font-size: 11px;
      padding: 10px 15px;
    }
    .comments [class*="level-"] .photo:before { background-color: #fff; }
    .comments .meta { color: #ccc; }
    .comments .meta a { color: inherit; }
    .comments .meta a:hover { color: #34b5d0; }
    .comments .body { color: #888; }
    
    /**
     * Comments Thread
     */
    .comments {
      list-style-type: none;
      padding: 5px 0 0 46px;
      position: relative;
      margin: 0 0 0 12px;
    }
    .comments:before,
    .comments .comment,
    .comments .comment:after,
    .comments .comment:before,
    .comments .photo img,
    .comments [class*="level-"] .photo:before {
      box-shadow: 0 1px 3px rgba(0,0,0,.4);
    }
    .comments:after,
    .comments:before {
      display: block;
      content: '';
      position: absolute;
    }
    .comments:before {
      border-radius: 0 0 5px 5px;
      height: 100%;
      width: 8px;
      left: 0;
      top: 0;
    }
    .comments:after {
      box-shadow: 0 1px 3px rgba(0,0,0,.4), 0 1px 3px rgba(0,0,0,.4) inset;
      border-width: 4px;
      border-style: solid;
      border-radius: 18px;
      height: 10px;
      width: 10px;
      left: -5px;
      top: -16px;
      z-index: -1;
    }
    .comments .comment {
      margin-bottom: 10px;
      position: relative;
    }
    .comments .comment:after,
    .comments .comment:before {
      border-radius: 10px;
      background-color: #fff;
      position: absolute;
      display: block;
      content: '';
    }
    .comments .comment:after {
      width: 12px;
      height: 12px;
      left: -14px;
      top: 7px;
    }
    .comments .comment:before {
      width: 5px;
      height: 5px;
      left: -22px;
      top: 16px;
    }
    .comments .photo {
      position: absolute;
      left: -60px;
      top: 2px;
    }
    .comments .photo img {
      border: 1px solid #fff;
      border-radius: 32px;
      overflow: hidden;
    }
    .comments .meta { margin-bottom: 5px; }
    .comments .meta .reply { display: none; float: right; }
    .comments .comment:hover .reply { display: block; }
    .comments [class*="level-"] .photo:before {
      display: block;
      content: '';
      position: absolute;
      margin-top: -2px;
      height: 4px;
      width: 20px;
      left: -10px;
      top: 50%;
      z-index: -1;
    }
    .comments .level-2 { margin-left: 30px; }
    .comments .level-3 { margin-left: 50px; }
    .comments .level-4 { margin-left: 70px; }
    .comments .level-5 { margin-left: 90px; }
    .comments .level-6 { margin-left: 110px; }
    .comments .level-3 .photo:before { width: 40px; left: -30px;}
    .comments .level-4 .photo:before { width: 60px; left: -50px;}
    .comments .level-5 .photo:before { width: 80px; left: -70px;}
    .comments .level-6 .photo:before { width: 100px; left: -90px;}
    
    

    public by micurs modified Oct 20, 2014  267527  11  7  1

    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 Snippets
    • Channels Snippets