├── .index.html.swp ├── LICENSE ├── ObjectControls.js ├── README.md ├── assests ├── GeosansLight.ttf └── note.mp3 ├── examples ├── displace.html ├── drag.html ├── highlight.html ├── highlightGroup.html └── noises.html ├── index.html └── lib ├── AudioController.js ├── LoadedAudio.js ├── three.min.js └── underscore.js /.index.html.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cabbibo/ObjectControls/7463aa75397433531e2014555c39be82469a8360/.index.html.swp -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright © 2015 Isaac Cohen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /ObjectControls.js: -------------------------------------------------------------------------------- 1 | // TODO Make it so you can pass in renderer w / h 2 | function ObjectControls( eye , params ){ 3 | 4 | this.intersected; 5 | this.selected; 6 | 7 | this.eye = eye; 8 | 9 | this.mouse = new THREE.Vector3(); 10 | this.unprojectedMouse = new THREE.Vector3(); 11 | 12 | this.objects = []; 13 | 14 | var params = params || {}; 15 | var p = params; 16 | 17 | this.domElement = p.domElement || document; 18 | 19 | // Recursively check descendants of objects in this.objects for intersections. 20 | this.recursive = p.recursive || false; 21 | 22 | this.raycaster = new THREE.Raycaster(); 23 | 24 | this.raycaster.near = this.eye.near; 25 | this.raycaster.far = this.eye.far; 26 | 27 | 28 | var addListener = this.domElement.addEventListener; 29 | 30 | var cb1 = this.mouseDown.bind( this ); 31 | var cb2 = this.mouseUp.bind( this ); 32 | var cb3 = this.mouseMove.bind( this ); 33 | 34 | this.domElement.addEventListener( 'mousedown', cb1 , false ) 35 | this.domElement.addEventListener( 'mouseup' , cb2 , false ) 36 | this.domElement.addEventListener( 'mousemove', cb3 , false ) 37 | 38 | this.domElement.addEventListener( 'touchdown', cb1 , false ) 39 | this.domElement.addEventListener( 'touchup' , cb2 , false ) 40 | this.domElement.addEventListener( 'touchmove', cb3 , false ) 41 | 42 | this.unprojectMouse(); 43 | 44 | } 45 | 46 | 47 | 48 | 49 | /* 50 | 51 | EVENTS 52 | 53 | */ 54 | 55 | 56 | // You can think of _up and _down as mouseup and mouse down 57 | ObjectControls.prototype._down = function(){ 58 | 59 | this.down(); 60 | 61 | if( this.intersected ){ 62 | 63 | this._select( this.intersected ); 64 | 65 | } 66 | 67 | } 68 | 69 | ObjectControls.prototype.down = function(){} 70 | 71 | 72 | 73 | ObjectControls.prototype._up = function(){ 74 | 75 | this.up(); 76 | 77 | if( this.selected ){ 78 | 79 | this._deselect( this.selected ); 80 | 81 | } 82 | 83 | } 84 | 85 | ObjectControls.prototype.up = function(){} 86 | 87 | 88 | 89 | ObjectControls.prototype._hoverOut = function( object ){ 90 | 91 | this.hoverOut(); 92 | 93 | this.objectHovered = false; 94 | 95 | if( object.hoverOut ){ 96 | object.hoverOut( this ); 97 | } 98 | 99 | }; 100 | 101 | ObjectControls.prototype.hoverOut = function(){}; 102 | 103 | 104 | 105 | ObjectControls.prototype._hoverOver = function( object ){ 106 | 107 | this.hoverOver(); 108 | 109 | this.objectHovered = true; 110 | 111 | if( object.hoverOver ){ 112 | object.hoverOver( this ); 113 | } 114 | 115 | }; 116 | 117 | ObjectControls.prototype.hoverOver = function(){} 118 | 119 | 120 | 121 | ObjectControls.prototype._select = function( object ){ 122 | 123 | this.select(); 124 | 125 | var intersectionPoint = this.getIntersectionPoint( this.intersected ); 126 | 127 | this.selected = object; 128 | this.intersectionPoint = intersectionPoint; 129 | 130 | if( object.select ){ 131 | object.select( this ); 132 | } 133 | 134 | }; 135 | 136 | ObjectControls.prototype.select = function(){} 137 | 138 | 139 | 140 | ObjectControls.prototype._deselect = function( object ){ 141 | 142 | //console.log('DESELECT'); 143 | 144 | this.selected = undefined; 145 | this.intersectionPoint = undefined; 146 | 147 | if( object.deselect ){ 148 | object.deselect( this ); 149 | } 150 | 151 | this.deselect(); 152 | 153 | }; 154 | 155 | ObjectControls.prototype.deselect = function(){} 156 | 157 | 158 | 159 | 160 | /* 161 | 162 | Changing what objects we are controlling 163 | 164 | */ 165 | 166 | ObjectControls.prototype.add = function( object ){ 167 | 168 | this.objects.push( object ); 169 | 170 | }; 171 | 172 | ObjectControls.prototype.remove = function( object ){ 173 | 174 | for( var i = 0; i < this.objects.length; i++ ){ 175 | 176 | if( this.objects[i] == object ){ 177 | 178 | this.objects.splice( i , 1 ); 179 | 180 | } 181 | 182 | } 183 | 184 | }; 185 | 186 | 187 | 188 | 189 | /* 190 | 191 | Update Loop 192 | 193 | */ 194 | 195 | ObjectControls.prototype.update = function(){ 196 | 197 | this.setRaycaster( this.unprojectedMouse ); 198 | if( !this.selected ){ 199 | 200 | this.checkForIntersections( this.unprojectedMouse ); 201 | 202 | }else{ 203 | 204 | this._updateSelected( this.unprojectedMouse ); 205 | 206 | } 207 | 208 | }; 209 | 210 | ObjectControls.prototype._updateSelected = function(){ 211 | 212 | if( this.selected.update ){ 213 | 214 | this.selected.update( this ); 215 | 216 | } 217 | 218 | } 219 | 220 | ObjectControls.prototype.updateSelected = function(){}; 221 | 222 | 223 | 224 | 225 | ObjectControls.prototype.setRaycaster = function( position ){ 226 | 227 | var origin = position; 228 | var direction = origin.clone() 229 | 230 | direction.sub( this.eye.position ); 231 | direction.normalize(); 232 | 233 | this.raycaster.set( this.eye.position , direction ); 234 | 235 | } 236 | 237 | 238 | 239 | /* 240 | 241 | Checks 242 | 243 | */ 244 | 245 | ObjectControls.prototype.checkForIntersections = function( position ){ 246 | 247 | var intersected = this.raycaster.intersectObjects( this.objects, this.recursive ); 248 | 249 | 250 | if( intersected.length > 0 ){ 251 | 252 | for (var n = 0; n < intersected.length; n++ ) { 253 | 254 | if ( this.recursive ) { 255 | 256 | var topLevelObj = this._findTopLevelAncestor( intersected[n].object ); 257 | if ( topLevelObj ) { 258 | 259 | // Reset intersected.object, leave intersected.point etc. unchanged. 260 | // This works since in the two most common use cases the ancestor: 261 | // (1) contains the child object (and the intersection point) 262 | // (2) is not a THREE.Mesh and thus doesn't appear in the scene, 263 | // e.g. an Object3D used for grouping other related objects. 264 | intersected[n].object = topLevelObj; 265 | 266 | } 267 | 268 | } 269 | 270 | } 271 | 272 | this._objectIntersected( intersected ); 273 | 274 | }else{ 275 | 276 | this._noObjectIntersected(); 277 | 278 | } 279 | 280 | }; 281 | 282 | ObjectControls.prototype.checkForUpDown = function( hand , oHand ){ 283 | 284 | if( this.upDownEvent( this.selectionStrength , hand , oHand ) === true ){ 285 | 286 | this._down(); 287 | 288 | }else if( this.upDownEvent( this.selectionStrength , hand , oHand ) === false ){ 289 | 290 | this._up(); 291 | 292 | } 293 | 294 | }; 295 | 296 | 297 | 298 | 299 | ObjectControls.prototype.getIntersectionPoint = function( i ){ 300 | 301 | var intersected = this.raycaster.intersectObjects( this.objects, this.recursive ); 302 | 303 | return intersected[0].point.sub( i.position ); 304 | 305 | } 306 | 307 | ObjectControls.prototype._findTopLevelAncestor = function( object ){ 308 | 309 | // Traverse back up until we find the first ancestor that is a top-level 310 | // object then return it (or null), since only top-level objects (which 311 | // were passed to objectControls.add) handle events, even if their child 312 | // objects are the ones intersected. 313 | 314 | while ( this.objects.indexOf(object) === -1) { 315 | 316 | if ( !object.parent ) { 317 | 318 | return null; 319 | 320 | } 321 | 322 | object = object.parent; 323 | 324 | } 325 | 326 | return object; 327 | 328 | } 329 | 330 | 331 | 332 | /* 333 | 334 | Raycast Events 335 | 336 | */ 337 | 338 | ObjectControls.prototype._objectIntersected = function( intersected ){ 339 | 340 | // Assigning out first intersected object 341 | // so we don't get changes everytime we hit 342 | // a new face 343 | var firstIntersection = intersected[0].object; 344 | 345 | if( !this.intersected ){ 346 | 347 | this.intersected = firstIntersection; 348 | 349 | this._hoverOver( this.intersected ); 350 | 351 | 352 | }else{ 353 | 354 | if( this.intersected != firstIntersection ){ 355 | 356 | this._hoverOut( this.intersected ); 357 | 358 | this.intersected = firstIntersection; 359 | 360 | this._hoverOver( this.intersected ); 361 | 362 | } 363 | 364 | } 365 | 366 | this.objectIntersected(); 367 | 368 | }; 369 | 370 | ObjectControls.prototype.objectIntersected = function(){} 371 | 372 | ObjectControls.prototype._noObjectIntersected = function(){ 373 | 374 | if( this.intersected ){ 375 | 376 | this._hoverOut( this.intersected ); 377 | this.intersected = undefined; 378 | 379 | } 380 | 381 | this.noObjectIntersected(); 382 | 383 | }; 384 | 385 | ObjectControls.prototype.noObjectIntersected = function(){} 386 | 387 | 388 | ObjectControls.prototype.mouseMove = function(event){ 389 | 390 | this.mouseMoved = true; 391 | 392 | this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; 393 | this.mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1; 394 | this.mouse.z = 1; 395 | 396 | this.unprojectMouse(); 397 | 398 | } 399 | 400 | ObjectControls.prototype.unprojectMouse = function(){ 401 | 402 | this.unprojectedMouse.copy( this.mouse ); 403 | this.unprojectedMouse.unproject( this.eye ); 404 | 405 | } 406 | 407 | ObjectControls.prototype.mouseDown = function( event ){ 408 | this.mouseMove( event ); 409 | this._down(); 410 | } 411 | 412 | ObjectControls.prototype.mouseUp = function(){ 413 | this.mouseMove( event ); 414 | this._up(); 415 | } 416 | 417 | 418 | ObjectControls.prototype.touchStart = function(event){ 419 | this.touchMove( event ); 420 | this._down(); 421 | } 422 | 423 | ObjectControls.prototype.touchEnd = function(event){ 424 | this.touchMove( event ); 425 | this._up(); 426 | } 427 | 428 | ObjectControls.prototype.touchMove= function(event){ 429 | 430 | this.mouseMoved = true; 431 | 432 | this.mouse.x = ( event.touches[ 0 ].pageX / window.innerWidth ) * 2 - 1; 433 | this.mouse.y = -( event.touches[ 0 ].pageY / window.innerHeight ) * 2 + 1; 434 | this.mouse.z = 1; 435 | 436 | this.unprojectMouse(); 437 | 438 | } 439 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ObjectControls 2 | 3 | Object Controls are a lightweight attempt to make manipulating objects in three.js slightly easier. I'm open to suggestions, and would love to hear if / how you use it, so please hit me up on [Twitter] if you have any questions / concerns / comments / general hatred. 4 | 5 | *[View Project on Github] 6 | 7 | 8 | Controlling objects in three.js is already very easy, and you can see some great examples of how to do it yourself by looking at some three.js examples: 9 | 10 | 11 | * [Threejs Draggable Cubes] 12 | * [ThreeJS BufferGeometry] 13 | 14 | 15 | But if you want to not have to implement it yourself, these controls are a great place to start! To see what can be done with them, Check out some of the following projects: 16 | 17 | * [cabbibo] - For intersection with all objects 18 | * [Growing Boy] - For figuring out mouse position in 3D 19 | * [Needs] - For selecting balls / songs 20 | * [DRAGONFISH] - For determining where creature moves 21 | 22 | There is also bunch more examples you can check out if you are more of a 'stare at the code' human being: 23 | 24 | * [Drag] - A basic Drag and Drop example 25 | * [Highlight] - The Most Basic example of highlighting different balls 26 | * [HighlightGroup] - Highlight groups of balls 27 | * [Displace] - Balls move away from your mouse when hit 28 | * [Noises] - make noises when you hit the objects 29 | 30 | But lets talk about how to actually use the code! 31 | 32 | ### Setup: 33 | 34 | First off include the script: 35 | ```javascript 36 | 37 | ``` 38 | 39 | Do all the thing that you would normally do with threejs, like setting up the renderer, scene and camera. Once you have done all this you can initialize the controls: 40 | 41 | ```javascript 42 | objectControls = new ObjectControls( camera ); 43 | ``` 44 | 45 | The 'camera' is passed into the ObjectControls , as the 'Eye' of the raycast. You could pass in a different 'eye' if you want, but it probably won't make too much sense... 46 | 47 | Within your 'animate' loop, make sure that you update the objectcontrols, like so: 48 | 49 | ```javascript 50 | objectControls.update(); 51 | ``` 52 | 53 | This is all you have to do to set up the Object Controls. But so far they don't do anything, so lets see how we can change that! 54 | 55 | ### How to use: 56 | 57 | The object controls are used by adding meshes to them. All of the logic of what happens when the meshes are interacted with is added to the mesh, so it controls itself! Here's a basic example of how to add meshes to the object controls: 58 | 59 | ```javascript 60 | var mat = new THREE.MeshNormalMaterial(); 61 | var geo = new THREE.IcosahedronGeometry( 10 , 1 ); 62 | var mesh = new THREE.Mesh( geo , mat ); 63 | objectControls.add( mesh ); 64 | 65 | 66 | // This is what will be called when 67 | // the mesh gets hovered over ( intersected 68 | mesh.hoverOver = function(){ 69 | 70 | } 71 | 72 | // This is what will get called when 73 | // the mesh gets hovered out ( unintersected ) 74 | mesh.hoverOut = function(){ 75 | 76 | } 77 | 78 | // This is what will be called if teh mesh 79 | // is both hovered, and the mousedown / touch happens 80 | mesh.select = function(){ 81 | 82 | } 83 | 84 | // This is what will be called if the mesh 85 | // is selected and than becomes 'deselected' 86 | // AKA the mouse gets released 87 | mesh.deselect = function(){ 88 | 89 | } 90 | 91 | 92 | // This is what will be called 93 | // every frame on the mesh while it is 94 | // selected 95 | mesh.update = function(){ 96 | 97 | } 98 | 99 | 100 | ``` 101 | 102 | In addition to controling a mesh as shown above, you can also control an Object3D with child meshes. Then events are triggered on the Object3D whenever any of its child meshes are intersected. To enable, set recursive:true in the params passed to the ObjectControls constructor, as shown in the [HighlightGroup] example. 103 | 104 | As usual, although the code is stable, this is still a work in progress, so if you see any problems, please please please let me know! Also, if there is something you want to see implemented, have any other suggestions, or use the code for anything I'd love to see how you used it, so hit me up on [Twitter] 105 | 106 | 107 | [Twitter]:http://twitter.com/cabbibo 108 | [cabbibo]:http://cabbi.bo/ 109 | [Growing Boy]:http://cabbi.bo/growingBoy 110 | [Needs]:http://cabbi.bo/Needs/ 111 | [DRAGONFISH]:http://cabbi.bo/DRAGONFISH 112 | 113 | [Drag]: http://cabbi.bo/ObjectControls/examples/drag.html 114 | [Highlight]: http://cabbi.bo/ObjectControls/examples/highlight.html 115 | [HighlightGroup]: http://cabbi.bo/ObjectControls/examples/highlightGroup.html 116 | [Displace]: http://cabbi.bo/ObjectControls/examples/displace.html 117 | [Noises]: http://cabbi.bo/ObjectControls/examples/noises.html 118 | 119 | [ThreeJS Draggable Cubes]: http://threejs.org/examples/#webgl_interactive_draggablecubes 120 | [ThreeJS BufferGeometry]: http://threejs.org/examples/#webgl_interactive_buffergeometry 121 | [View Project on Github]: http://github.com/cabbibo/ObjectControls 122 | -------------------------------------------------------------------------------- /assests/GeosansLight.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cabbibo/ObjectControls/7463aa75397433531e2014555c39be82469a8360/assests/GeosansLight.ttf -------------------------------------------------------------------------------- /assests/note.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cabbibo/ObjectControls/7463aa75397433531e2014555c39be82469a8360/assests/note.mp3 -------------------------------------------------------------------------------- /examples/displace.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /examples/drag.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /examples/highlight.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /examples/highlightGroup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /examples/noises.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 41 | 42 | 43 | 44 | 45 |
49 |

ObjectControls

50 |

Object Controls are a lightweight attempt to make manipulating objects in three.js slightly easier. I'm open to suggestions, and would love to hear if / how you use it, so please hit me up on Twitter if you have any questions / concerns / comments / general hatred.

51 |

*View Project on Github

52 |

Controlling objects in three.js is already very easy, and you can see some great examples of how to do it yourself by looking at some three.js examples:

53 | 57 |

But if you want to not have to implement it yourself, these controls are a great place to start! To see what can be done with them, Check out some of the following projects:

58 | 64 |

There is also bunch more examples you can check out if you are more of a 'stare at the code' human being:

65 | 72 |

But lets talk about how to actually use the code!

73 |

Setup:

74 |

First off include the script:

75 |
<script src="PATH/TO/ObjectControls.js"></script>
 76 |   
77 |

Do all the thing that you would normally do with threejs, like setting up the renderer, scene and camera. Once you have done all this you can initialize the controls:

78 |
    objectControls = new ObjectControls( camera );
 79 |   
80 |

The 'camera' is passed into the ObjectControls , as the 'Eye' of the raycast. You could pass in a different 'eye' if you want, but it probably won't make too much sense...

81 |

Within your 'animate' loop, make sure that you update the objectcontrols, like so:

82 |
    objectControls.update();
 83 |   
84 |

This is all you have to do to set up the Object Controls. But so far they don't do anything, so lets see how we can change that!

85 |

How to use:

86 |

The object controls are used by adding meshes to them. All of the logic of what happens when the meshes are interacted with is added to the mesh, so it controls itself! Here's a basic example of how to add meshes to the object controls:

87 |
      var mat = new THREE.MeshNormalMaterial();
 88 |       var geo = new THREE.IcosahedronGeometry( 10 , 1 );
 89 |       var mesh = new THREE.Mesh( geo , mat );
 90 | 
 91 | 
 92 |       // This is what will be called when
 93 |       // the mesh gets hovered over ( intersected
 94 |       mesh.hoverOver = function(){
 95 | 
 96 |       }
 97 | 
 98 |       // This is what will get called when
 99 |       // the mesh gets hovered out ( unintersected )
100 |       mesh.hoverOut = function(){
101 | 
102 |       }
103 | 
104 |       // This is what will be called if teh mesh
105 |       // is both hovered, and the mousedown / touch happens
106 |       mesh.select = function(){
107 | 
108 |       }
109 | 
110 |       // This is what will be called if the mesh
111 |       // is selected and than becomes 'deselected' 
112 |       // AKA the mouse gets released
113 |       mesh.deselect = function(){
114 | 
115 |       }
116 | 
117 | 
118 |       // This is what will be called
119 |       // every frame on the mesh while it is
120 |       // selected
121 |       mesh.update = function(){
122 | 
123 |       }
124 |   
125 |

In addition to controling a mesh as shown above, you can also control an Object3D with child meshes. Then events are triggered on the Object3D whenever any of its child meshes are intersected. To enable, set recursive:true in the params passed to the ObjectControls constructor, as shown in the HighlightGroup example.

126 |

As usual, although the code is stable, this is still a work in progress, so if you see any problems, please please please let me know! Also, if there is something you want to see implemented, have any other suggestions, or use the code for anything I'd love to see how you used it, so hit me up on Twitter

127 |
128 | 129 | 130 | 131 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | -------------------------------------------------------------------------------- /lib/AudioController.js: -------------------------------------------------------------------------------- 1 | function AudioController(){ 2 | 3 | //if( 4 | try { 5 | window.AudioContext = window.AudioContext ||window.webkitAudioContext; 6 | }catch(e) { 7 | alert( 'WEB AUDIO API NOT SUPPORTED' ); 8 | } 9 | 10 | this.ctx = new AudioContext(); 11 | 12 | this.gain = this.ctx.createGain(); 13 | 14 | this.gain.connect( this.ctx.destination ); 15 | 16 | this.updateArray = []; 17 | 18 | this.notes = []; 19 | 20 | } 21 | 22 | 23 | AudioController.prototype.update = function(){ 24 | 25 | 26 | for( var i = 0; i < this.notes.length; i++ ){ 27 | 28 | this.notes[i].update(); 29 | 30 | } 31 | 32 | for( var i = 0; i < this.updateArray.length; i++ ){ 33 | 34 | this.updateArray[i](); 35 | 36 | } 37 | 38 | 39 | 40 | } 41 | 42 | AudioController.prototype.addToUpdateArray = function( callback ){ 43 | 44 | this.updateArray.push( callback ); 45 | 46 | } 47 | 48 | AudioController.prototype.removeFromUpdateArray = function( callback ){ 49 | 50 | for( var i = 0; i< this.updateArray.length; i++ ){ 51 | 52 | if( this.updateArray[i] === callback ){ 53 | 54 | this.updateArray.splice( i , 1 ); 55 | //console.log( 'SPLICED' ); 56 | 57 | }else{ 58 | 59 | //console.log('NO'); 60 | 61 | } 62 | 63 | } 64 | 65 | } 66 | 67 | 68 | -------------------------------------------------------------------------------- /lib/LoadedAudio.js: -------------------------------------------------------------------------------- 1 | // TODO: Best way to update 2 | 3 | function LoadedAudio( controller , file , params ){ 4 | 5 | this.loader; 6 | this.controller = controller; 7 | 8 | this.params = _.defaults( params || {}, { 9 | 10 | looping: false, 11 | fbc: 128, 12 | fadeTime: 1, 13 | texture: true, 14 | output: this.controller.gain 15 | 16 | }); 17 | 18 | this.hasLoaded = false; 19 | 20 | this.file = file; 21 | 22 | this.playing = false; 23 | 24 | this.looping = this.params.looping; 25 | 26 | this.output = this.params.output; 27 | 28 | this.buffer; 29 | 30 | this.filterOn = false; 31 | this.gain = this.controller.ctx.createGain(); 32 | 33 | this.gain.connect( this.output ); 34 | 35 | 36 | this.time = 0; 37 | 38 | 39 | this.loadFile(); 40 | 41 | } 42 | 43 | LoadedAudio.prototype.reconnect = function( newOutput ){ 44 | 45 | this.gain.disconnect( this.output ); 46 | this.output = newOutput; 47 | this.gain.connect( this.output ); 48 | 49 | } 50 | 51 | LoadedAudio.prototype._loadProgress = function(e){ 52 | 53 | this.loaded = e.loaded / e.total; 54 | 55 | this.loadProgress( e ); 56 | 57 | //tween.start(); 58 | } 59 | 60 | LoadedAudio.prototype.loadProgress = function(){} 61 | 62 | 63 | LoadedAudio.prototype.loadFile = function(){ 64 | 65 | 66 | var request=new XMLHttpRequest(); 67 | request.open("GET",this.file,true); 68 | request.responseType="arraybuffer"; 69 | 70 | var self = this; 71 | request.onerror = function(){ 72 | alert( 'ERROR LOADING SONG' ); 73 | //self.womb.loader.addFailue( 'Capability to load song' , 'http://womble.com' 74 | } 75 | 76 | 77 | 78 | request.onprogress = this._loadProgress.bind( this ); 79 | 80 | var self = this; 81 | 82 | request.onload = function(){ 83 | 84 | self.controller.ctx.decodeAudioData(request.response,function(buffer){ 85 | 86 | if(!buffer){ 87 | alert('error decoding file data: '+url); 88 | return; 89 | } 90 | 91 | self.buffer = buffer; 92 | self.onDecode(); 93 | 94 | }) 95 | }, 96 | 97 | request.send(); 98 | 99 | } 100 | 101 | LoadedAudio.prototype.onDecode = function(){ 102 | 103 | //gets just the track name, removing the mp3 104 | this.trackID= this.file.split('.')[this.file.split('.').length-2]; 105 | 106 | this.createSource(); 107 | 108 | //var self = this; 109 | //if( this.params.onLoad ) this.params.onLoad( self ); 110 | 111 | this._onLoad(); 112 | 113 | } 114 | 115 | LoadedAudio.prototype.createSource = function() { 116 | 117 | this.source = this.controller.ctx.createBufferSource(); 118 | this.source.buffer = this.buffer; 119 | this.source.loop = false;//this.looping; 120 | 121 | this.source.connect( this.gain ); 122 | 123 | /*if( !this.looping ){ 124 | 125 | this.gain.gain.value = 1; 126 | }*/ 127 | 128 | //this.gain.connect( this.analyser ); 129 | 130 | }; 131 | 132 | LoadedAudio.prototype.destroySource = function(){ 133 | 134 | console.log( 'DESTROY' ); 135 | this.source.disconnect(this.gain); 136 | this.source = undefined; 137 | 138 | }; 139 | 140 | 141 | 142 | LoadedAudio.prototype.stop = function(){ 143 | 144 | this.playing = false; 145 | 146 | this.source.stop(); 147 | 148 | this.createSource(); 149 | 150 | }; 151 | 152 | LoadedAudio.prototype.play = function(){ 153 | 154 | //this.startTime = this.controller.womb.time.value; 155 | 156 | this.playing = true; 157 | 158 | this.source.start(0); 159 | 160 | // Creates a new source for the audio right away 161 | // so we can play the next one with no delay 162 | // if(this.source.loop == false){ 163 | this.createSource(); 164 | // } 165 | // 166 | //this.controller.addToUpdateArray( this.update.bind( this ) ); 167 | 168 | }; 169 | 170 | LoadedAudio.prototype._onLoad = function(){ 171 | 172 | if( this.looping ){ 173 | 174 | 175 | looper.everyLoop( function(){ 176 | 177 | if( this.playing ){ 178 | this.play() 179 | } 180 | 181 | }.bind( this )); 182 | 183 | this.gain.gain.value = 0; 184 | 185 | } 186 | 187 | this.hasLoaded = true; 188 | 189 | this.onLoad(); 190 | 191 | //this.controller.addToUpdateArray( this.update.bind( this ) ); 192 | 193 | } 194 | LoadedAudio.prototype.onLoad = function(){} 195 | 196 | 197 | LoadedAudio.prototype.update = function(){ 198 | 199 | if( this.playing ){ 200 | 201 | } 202 | 203 | } 204 | 205 | -------------------------------------------------------------------------------- /lib/underscore.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.5.2 2 | // http://underscorejs.org 3 | // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4 | // Underscore may be freely distributed under the MIT license. 5 | 6 | (function() { 7 | 8 | // Baseline setup 9 | // -------------- 10 | 11 | // Establish the root object, `window` in the browser, or `exports` on the server. 12 | var root = this; 13 | 14 | // Save the previous value of the `_` variable. 15 | var previousUnderscore = root._; 16 | 17 | // Establish the object that gets returned to break out of a loop iteration. 18 | var breaker = {}; 19 | 20 | // Save bytes in the minified (but not gzipped) version: 21 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 22 | 23 | // Create quick reference variables for speed access to core prototypes. 24 | var 25 | push = ArrayProto.push, 26 | slice = ArrayProto.slice, 27 | concat = ArrayProto.concat, 28 | toString = ObjProto.toString, 29 | hasOwnProperty = ObjProto.hasOwnProperty; 30 | 31 | // All **ECMAScript 5** native function implementations that we hope to use 32 | // are declared here. 33 | var 34 | nativeForEach = ArrayProto.forEach, 35 | nativeMap = ArrayProto.map, 36 | nativeReduce = ArrayProto.reduce, 37 | nativeReduceRight = ArrayProto.reduceRight, 38 | nativeFilter = ArrayProto.filter, 39 | nativeEvery = ArrayProto.every, 40 | nativeSome = ArrayProto.some, 41 | nativeIndexOf = ArrayProto.indexOf, 42 | nativeLastIndexOf = ArrayProto.lastIndexOf, 43 | nativeIsArray = Array.isArray, 44 | nativeKeys = Object.keys, 45 | nativeBind = FuncProto.bind; 46 | 47 | // Create a safe reference to the Underscore object for use below. 48 | var _ = function(obj) { 49 | if (obj instanceof _) return obj; 50 | if (!(this instanceof _)) return new _(obj); 51 | this._wrapped = obj; 52 | }; 53 | 54 | // Export the Underscore object for **Node.js**, with 55 | // backwards-compatibility for the old `require()` API. If we're in 56 | // the browser, add `_` as a global object via a string identifier, 57 | // for Closure Compiler "advanced" mode. 58 | if (typeof exports !== 'undefined') { 59 | if (typeof module !== 'undefined' && module.exports) { 60 | exports = module.exports = _; 61 | } 62 | exports._ = _; 63 | } else { 64 | root._ = _; 65 | } 66 | 67 | // Current version. 68 | _.VERSION = '1.5.2'; 69 | 70 | // Collection Functions 71 | // -------------------- 72 | 73 | // The cornerstone, an `each` implementation, aka `forEach`. 74 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 75 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 76 | var each = _.each = _.forEach = function(obj, iterator, context) { 77 | if (obj == null) return; 78 | if (nativeForEach && obj.forEach === nativeForEach) { 79 | obj.forEach(iterator, context); 80 | } else if (obj.length === +obj.length) { 81 | for (var i = 0, length = obj.length; i < length; i++) { 82 | if (iterator.call(context, obj[i], i, obj) === breaker) return; 83 | } 84 | } else { 85 | var keys = _.keys(obj); 86 | for (var i = 0, length = keys.length; i < length; i++) { 87 | if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; 88 | } 89 | } 90 | }; 91 | 92 | // Return the results of applying the iterator to each element. 93 | // Delegates to **ECMAScript 5**'s native `map` if available. 94 | _.map = _.collect = function(obj, iterator, context) { 95 | var results = []; 96 | if (obj == null) return results; 97 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 98 | each(obj, function(value, index, list) { 99 | results.push(iterator.call(context, value, index, list)); 100 | }); 101 | return results; 102 | }; 103 | 104 | var reduceError = 'Reduce of empty array with no initial value'; 105 | 106 | // **Reduce** builds up a single result from a list of values, aka `inject`, 107 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 108 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 109 | var initial = arguments.length > 2; 110 | if (obj == null) obj = []; 111 | if (nativeReduce && obj.reduce === nativeReduce) { 112 | if (context) iterator = _.bind(iterator, context); 113 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 114 | } 115 | each(obj, function(value, index, list) { 116 | if (!initial) { 117 | memo = value; 118 | initial = true; 119 | } else { 120 | memo = iterator.call(context, memo, value, index, list); 121 | } 122 | }); 123 | if (!initial) throw new TypeError(reduceError); 124 | return memo; 125 | }; 126 | 127 | // The right-associative version of reduce, also known as `foldr`. 128 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 129 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 130 | var initial = arguments.length > 2; 131 | if (obj == null) obj = []; 132 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 133 | if (context) iterator = _.bind(iterator, context); 134 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 135 | } 136 | var length = obj.length; 137 | if (length !== +length) { 138 | var keys = _.keys(obj); 139 | length = keys.length; 140 | } 141 | each(obj, function(value, index, list) { 142 | index = keys ? keys[--length] : --length; 143 | if (!initial) { 144 | memo = obj[index]; 145 | initial = true; 146 | } else { 147 | memo = iterator.call(context, memo, obj[index], index, list); 148 | } 149 | }); 150 | if (!initial) throw new TypeError(reduceError); 151 | return memo; 152 | }; 153 | 154 | // Return the first value which passes a truth test. Aliased as `detect`. 155 | _.find = _.detect = function(obj, iterator, context) { 156 | var result; 157 | any(obj, function(value, index, list) { 158 | if (iterator.call(context, value, index, list)) { 159 | result = value; 160 | return true; 161 | } 162 | }); 163 | return result; 164 | }; 165 | 166 | // Return all the elements that pass a truth test. 167 | // Delegates to **ECMAScript 5**'s native `filter` if available. 168 | // Aliased as `select`. 169 | _.filter = _.select = function(obj, iterator, context) { 170 | var results = []; 171 | if (obj == null) return results; 172 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); 173 | each(obj, function(value, index, list) { 174 | if (iterator.call(context, value, index, list)) results.push(value); 175 | }); 176 | return results; 177 | }; 178 | 179 | // Return all the elements for which a truth test fails. 180 | _.reject = function(obj, iterator, context) { 181 | return _.filter(obj, function(value, index, list) { 182 | return !iterator.call(context, value, index, list); 183 | }, context); 184 | }; 185 | 186 | // Determine whether all of the elements match a truth test. 187 | // Delegates to **ECMAScript 5**'s native `every` if available. 188 | // Aliased as `all`. 189 | _.every = _.all = function(obj, iterator, context) { 190 | iterator || (iterator = _.identity); 191 | var result = true; 192 | if (obj == null) return result; 193 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); 194 | each(obj, function(value, index, list) { 195 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; 196 | }); 197 | return !!result; 198 | }; 199 | 200 | // Determine if at least one element in the object matches a truth test. 201 | // Delegates to **ECMAScript 5**'s native `some` if available. 202 | // Aliased as `any`. 203 | var any = _.some = _.any = function(obj, iterator, context) { 204 | iterator || (iterator = _.identity); 205 | var result = false; 206 | if (obj == null) return result; 207 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); 208 | each(obj, function(value, index, list) { 209 | if (result || (result = iterator.call(context, value, index, list))) return breaker; 210 | }); 211 | return !!result; 212 | }; 213 | 214 | // Determine if the array or object contains a given value (using `===`). 215 | // Aliased as `include`. 216 | _.contains = _.include = function(obj, target) { 217 | if (obj == null) return false; 218 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 219 | return any(obj, function(value) { 220 | return value === target; 221 | }); 222 | }; 223 | 224 | // Invoke a method (with arguments) on every item in a collection. 225 | _.invoke = function(obj, method) { 226 | var args = slice.call(arguments, 2); 227 | var isFunc = _.isFunction(method); 228 | return _.map(obj, function(value) { 229 | return (isFunc ? method : value[method]).apply(value, args); 230 | }); 231 | }; 232 | 233 | // Convenience version of a common use case of `map`: fetching a property. 234 | _.pluck = function(obj, key) { 235 | return _.map(obj, function(value){ return value[key]; }); 236 | }; 237 | 238 | // Convenience version of a common use case of `filter`: selecting only objects 239 | // containing specific `key:value` pairs. 240 | _.where = function(obj, attrs, first) { 241 | if (_.isEmpty(attrs)) return first ? void 0 : []; 242 | return _[first ? 'find' : 'filter'](obj, function(value) { 243 | for (var key in attrs) { 244 | if (attrs[key] !== value[key]) return false; 245 | } 246 | return true; 247 | }); 248 | }; 249 | 250 | // Convenience version of a common use case of `find`: getting the first object 251 | // containing specific `key:value` pairs. 252 | _.findWhere = function(obj, attrs) { 253 | return _.where(obj, attrs, true); 254 | }; 255 | 256 | // Return the maximum element or (element-based computation). 257 | // Can't optimize arrays of integers longer than 65,535 elements. 258 | // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) 259 | _.max = function(obj, iterator, context) { 260 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 261 | return Math.max.apply(Math, obj); 262 | } 263 | if (!iterator && _.isEmpty(obj)) return -Infinity; 264 | var result = {computed : -Infinity, value: -Infinity}; 265 | each(obj, function(value, index, list) { 266 | var computed = iterator ? iterator.call(context, value, index, list) : value; 267 | computed > result.computed && (result = {value : value, computed : computed}); 268 | }); 269 | return result.value; 270 | }; 271 | 272 | // Return the minimum element (or element-based computation). 273 | _.min = function(obj, iterator, context) { 274 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 275 | return Math.min.apply(Math, obj); 276 | } 277 | if (!iterator && _.isEmpty(obj)) return Infinity; 278 | var result = {computed : Infinity, value: Infinity}; 279 | each(obj, function(value, index, list) { 280 | var computed = iterator ? iterator.call(context, value, index, list) : value; 281 | computed < result.computed && (result = {value : value, computed : computed}); 282 | }); 283 | return result.value; 284 | }; 285 | 286 | // Shuffle an array, using the modern version of the 287 | // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). 288 | _.shuffle = function(obj) { 289 | var rand; 290 | var index = 0; 291 | var shuffled = []; 292 | each(obj, function(value) { 293 | rand = _.random(index++); 294 | shuffled[index - 1] = shuffled[rand]; 295 | shuffled[rand] = value; 296 | }); 297 | return shuffled; 298 | }; 299 | 300 | // Sample **n** random values from a collection. 301 | // If **n** is not specified, returns a single random element. 302 | // The internal `guard` argument allows it to work with `map`. 303 | _.sample = function(obj, n, guard) { 304 | if (n == null || guard) { 305 | if (obj.length !== +obj.length) obj = _.values(obj); 306 | return obj[_.random(obj.length - 1)]; 307 | } 308 | return _.shuffle(obj).slice(0, Math.max(0, n)); 309 | }; 310 | 311 | // An internal function to generate lookup iterators. 312 | var lookupIterator = function(value) { 313 | return _.isFunction(value) ? value : function(obj){ return obj[value]; }; 314 | }; 315 | 316 | // Sort the object's values by a criterion produced by an iterator. 317 | _.sortBy = function(obj, value, context) { 318 | var iterator = lookupIterator(value); 319 | return _.pluck(_.map(obj, function(value, index, list) { 320 | return { 321 | value: value, 322 | index: index, 323 | criteria: iterator.call(context, value, index, list) 324 | }; 325 | }).sort(function(left, right) { 326 | var a = left.criteria; 327 | var b = right.criteria; 328 | if (a !== b) { 329 | if (a > b || a === void 0) return 1; 330 | if (a < b || b === void 0) return -1; 331 | } 332 | return left.index - right.index; 333 | }), 'value'); 334 | }; 335 | 336 | // An internal function used for aggregate "group by" operations. 337 | var group = function(behavior) { 338 | return function(obj, value, context) { 339 | var result = {}; 340 | var iterator = value == null ? _.identity : lookupIterator(value); 341 | each(obj, function(value, index) { 342 | var key = iterator.call(context, value, index, obj); 343 | behavior(result, key, value); 344 | }); 345 | return result; 346 | }; 347 | }; 348 | 349 | // Groups the object's values by a criterion. Pass either a string attribute 350 | // to group by, or a function that returns the criterion. 351 | _.groupBy = group(function(result, key, value) { 352 | (_.has(result, key) ? result[key] : (result[key] = [])).push(value); 353 | }); 354 | 355 | // Indexes the object's values by a criterion, similar to `groupBy`, but for 356 | // when you know that your index values will be unique. 357 | _.indexBy = group(function(result, key, value) { 358 | result[key] = value; 359 | }); 360 | 361 | // Counts instances of an object that group by a certain criterion. Pass 362 | // either a string attribute to count by, or a function that returns the 363 | // criterion. 364 | _.countBy = group(function(result, key) { 365 | _.has(result, key) ? result[key]++ : result[key] = 1; 366 | }); 367 | 368 | // Use a comparator function to figure out the smallest index at which 369 | // an object should be inserted so as to maintain order. Uses binary search. 370 | _.sortedIndex = function(array, obj, iterator, context) { 371 | iterator = iterator == null ? _.identity : lookupIterator(iterator); 372 | var value = iterator.call(context, obj); 373 | var low = 0, high = array.length; 374 | while (low < high) { 375 | var mid = (low + high) >>> 1; 376 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; 377 | } 378 | return low; 379 | }; 380 | 381 | // Safely create a real, live array from anything iterable. 382 | _.toArray = function(obj) { 383 | if (!obj) return []; 384 | if (_.isArray(obj)) return slice.call(obj); 385 | if (obj.length === +obj.length) return _.map(obj, _.identity); 386 | return _.values(obj); 387 | }; 388 | 389 | // Return the number of elements in an object. 390 | _.size = function(obj) { 391 | if (obj == null) return 0; 392 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; 393 | }; 394 | 395 | // Array Functions 396 | // --------------- 397 | 398 | // Get the first element of an array. Passing **n** will return the first N 399 | // values in the array. Aliased as `head` and `take`. The **guard** check 400 | // allows it to work with `_.map`. 401 | _.first = _.head = _.take = function(array, n, guard) { 402 | if (array == null) return void 0; 403 | return (n == null) || guard ? array[0] : slice.call(array, 0, n); 404 | }; 405 | 406 | // Returns everything but the last entry of the array. Especially useful on 407 | // the arguments object. Passing **n** will return all the values in 408 | // the array, excluding the last N. The **guard** check allows it to work with 409 | // `_.map`. 410 | _.initial = function(array, n, guard) { 411 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 412 | }; 413 | 414 | // Get the last element of an array. Passing **n** will return the last N 415 | // values in the array. The **guard** check allows it to work with `_.map`. 416 | _.last = function(array, n, guard) { 417 | if (array == null) return void 0; 418 | if ((n == null) || guard) { 419 | return array[array.length - 1]; 420 | } else { 421 | return slice.call(array, Math.max(array.length - n, 0)); 422 | } 423 | }; 424 | 425 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 426 | // Especially useful on the arguments object. Passing an **n** will return 427 | // the rest N values in the array. The **guard** 428 | // check allows it to work with `_.map`. 429 | _.rest = _.tail = _.drop = function(array, n, guard) { 430 | return slice.call(array, (n == null) || guard ? 1 : n); 431 | }; 432 | 433 | // Trim out all falsy values from an array. 434 | _.compact = function(array) { 435 | return _.filter(array, _.identity); 436 | }; 437 | 438 | // Internal implementation of a recursive `flatten` function. 439 | var flatten = function(input, shallow, output) { 440 | if (shallow && _.every(input, _.isArray)) { 441 | return concat.apply(output, input); 442 | } 443 | each(input, function(value) { 444 | if (_.isArray(value) || _.isArguments(value)) { 445 | shallow ? push.apply(output, value) : flatten(value, shallow, output); 446 | } else { 447 | output.push(value); 448 | } 449 | }); 450 | return output; 451 | }; 452 | 453 | // Flatten out an array, either recursively (by default), or just one level. 454 | _.flatten = function(array, shallow) { 455 | return flatten(array, shallow, []); 456 | }; 457 | 458 | // Return a version of the array that does not contain the specified value(s). 459 | _.without = function(array) { 460 | return _.difference(array, slice.call(arguments, 1)); 461 | }; 462 | 463 | // Produce a duplicate-free version of the array. If the array has already 464 | // been sorted, you have the option of using a faster algorithm. 465 | // Aliased as `unique`. 466 | _.uniq = _.unique = function(array, isSorted, iterator, context) { 467 | if (_.isFunction(isSorted)) { 468 | context = iterator; 469 | iterator = isSorted; 470 | isSorted = false; 471 | } 472 | var initial = iterator ? _.map(array, iterator, context) : array; 473 | var results = []; 474 | var seen = []; 475 | each(initial, function(value, index) { 476 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { 477 | seen.push(value); 478 | results.push(array[index]); 479 | } 480 | }); 481 | return results; 482 | }; 483 | 484 | // Produce an array that contains the union: each distinct element from all of 485 | // the passed-in arrays. 486 | _.union = function() { 487 | return _.uniq(_.flatten(arguments, true)); 488 | }; 489 | 490 | // Produce an array that contains every item shared between all the 491 | // passed-in arrays. 492 | _.intersection = function(array) { 493 | var rest = slice.call(arguments, 1); 494 | return _.filter(_.uniq(array), function(item) { 495 | return _.every(rest, function(other) { 496 | return _.indexOf(other, item) >= 0; 497 | }); 498 | }); 499 | }; 500 | 501 | // Take the difference between one array and a number of other arrays. 502 | // Only the elements present in just the first array will remain. 503 | _.difference = function(array) { 504 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); 505 | return _.filter(array, function(value){ return !_.contains(rest, value); }); 506 | }; 507 | 508 | // Zip together multiple lists into a single array -- elements that share 509 | // an index go together. 510 | _.zip = function() { 511 | var length = _.max(_.pluck(arguments, "length").concat(0)); 512 | var results = new Array(length); 513 | for (var i = 0; i < length; i++) { 514 | results[i] = _.pluck(arguments, '' + i); 515 | } 516 | return results; 517 | }; 518 | 519 | // Converts lists into objects. Pass either a single array of `[key, value]` 520 | // pairs, or two parallel arrays of the same length -- one of keys, and one of 521 | // the corresponding values. 522 | _.object = function(list, values) { 523 | if (list == null) return {}; 524 | var result = {}; 525 | for (var i = 0, length = list.length; i < length; i++) { 526 | if (values) { 527 | result[list[i]] = values[i]; 528 | } else { 529 | result[list[i][0]] = list[i][1]; 530 | } 531 | } 532 | return result; 533 | }; 534 | 535 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 536 | // we need this function. Return the position of the first occurrence of an 537 | // item in an array, or -1 if the item is not included in the array. 538 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 539 | // If the array is large and already in sort order, pass `true` 540 | // for **isSorted** to use binary search. 541 | _.indexOf = function(array, item, isSorted) { 542 | if (array == null) return -1; 543 | var i = 0, length = array.length; 544 | if (isSorted) { 545 | if (typeof isSorted == 'number') { 546 | i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); 547 | } else { 548 | i = _.sortedIndex(array, item); 549 | return array[i] === item ? i : -1; 550 | } 551 | } 552 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); 553 | for (; i < length; i++) if (array[i] === item) return i; 554 | return -1; 555 | }; 556 | 557 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 558 | _.lastIndexOf = function(array, item, from) { 559 | if (array == null) return -1; 560 | var hasIndex = from != null; 561 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { 562 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); 563 | } 564 | var i = (hasIndex ? from : array.length); 565 | while (i--) if (array[i] === item) return i; 566 | return -1; 567 | }; 568 | 569 | // Generate an integer Array containing an arithmetic progression. A port of 570 | // the native Python `range()` function. See 571 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 572 | _.range = function(start, stop, step) { 573 | if (arguments.length <= 1) { 574 | stop = start || 0; 575 | start = 0; 576 | } 577 | step = arguments[2] || 1; 578 | 579 | var length = Math.max(Math.ceil((stop - start) / step), 0); 580 | var idx = 0; 581 | var range = new Array(length); 582 | 583 | while(idx < length) { 584 | range[idx++] = start; 585 | start += step; 586 | } 587 | 588 | return range; 589 | }; 590 | 591 | // Function (ahem) Functions 592 | // ------------------ 593 | 594 | // Reusable constructor function for prototype setting. 595 | var ctor = function(){}; 596 | 597 | // Create a function bound to a given object (assigning `this`, and arguments, 598 | // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if 599 | // available. 600 | _.bind = function(func, context) { 601 | var args, bound; 602 | if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 603 | if (!_.isFunction(func)) throw new TypeError; 604 | args = slice.call(arguments, 2); 605 | return bound = function() { 606 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 607 | ctor.prototype = func.prototype; 608 | var self = new ctor; 609 | ctor.prototype = null; 610 | var result = func.apply(self, args.concat(slice.call(arguments))); 611 | if (Object(result) === result) return result; 612 | return self; 613 | }; 614 | }; 615 | 616 | // Partially apply a function by creating a version that has had some of its 617 | // arguments pre-filled, without changing its dynamic `this` context. 618 | _.partial = function(func) { 619 | var args = slice.call(arguments, 1); 620 | return function() { 621 | return func.apply(this, args.concat(slice.call(arguments))); 622 | }; 623 | }; 624 | 625 | // Bind all of an object's methods to that object. Useful for ensuring that 626 | // all callbacks defined on an object belong to it. 627 | _.bindAll = function(obj) { 628 | var funcs = slice.call(arguments, 1); 629 | if (funcs.length === 0) throw new Error("bindAll must be passed function names"); 630 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 631 | return obj; 632 | }; 633 | 634 | // Memoize an expensive function by storing its results. 635 | _.memoize = function(func, hasher) { 636 | var memo = {}; 637 | hasher || (hasher = _.identity); 638 | return function() { 639 | var key = hasher.apply(this, arguments); 640 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 641 | }; 642 | }; 643 | 644 | // Delays a function for the given number of milliseconds, and then calls 645 | // it with the arguments supplied. 646 | _.delay = function(func, wait) { 647 | var args = slice.call(arguments, 2); 648 | return setTimeout(function(){ return func.apply(null, args); }, wait); 649 | }; 650 | 651 | // Defers a function, scheduling it to run after the current call stack has 652 | // cleared. 653 | _.defer = function(func) { 654 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 655 | }; 656 | 657 | // Returns a function, that, when invoked, will only be triggered at most once 658 | // during a given window of time. Normally, the throttled function will run 659 | // as much as it can, without ever going more than once per `wait` duration; 660 | // but if you'd like to disable the execution on the leading edge, pass 661 | // `{leading: false}`. To disable execution on the trailing edge, ditto. 662 | _.throttle = function(func, wait, options) { 663 | var context, args, result; 664 | var timeout = null; 665 | var previous = 0; 666 | options || (options = {}); 667 | var later = function() { 668 | previous = options.leading === false ? 0 : new Date; 669 | timeout = null; 670 | result = func.apply(context, args); 671 | }; 672 | return function() { 673 | var now = new Date; 674 | if (!previous && options.leading === false) previous = now; 675 | var remaining = wait - (now - previous); 676 | context = this; 677 | args = arguments; 678 | if (remaining <= 0) { 679 | clearTimeout(timeout); 680 | timeout = null; 681 | previous = now; 682 | result = func.apply(context, args); 683 | } else if (!timeout && options.trailing !== false) { 684 | timeout = setTimeout(later, remaining); 685 | } 686 | return result; 687 | }; 688 | }; 689 | 690 | // Returns a function, that, as long as it continues to be invoked, will not 691 | // be triggered. The function will be called after it stops being called for 692 | // N milliseconds. If `immediate` is passed, trigger the function on the 693 | // leading edge, instead of the trailing. 694 | _.debounce = function(func, wait, immediate) { 695 | var timeout, args, context, timestamp, result; 696 | return function() { 697 | context = this; 698 | args = arguments; 699 | timestamp = new Date(); 700 | var later = function() { 701 | var last = (new Date()) - timestamp; 702 | if (last < wait) { 703 | timeout = setTimeout(later, wait - last); 704 | } else { 705 | timeout = null; 706 | if (!immediate) result = func.apply(context, args); 707 | } 708 | }; 709 | var callNow = immediate && !timeout; 710 | if (!timeout) { 711 | timeout = setTimeout(later, wait); 712 | } 713 | if (callNow) result = func.apply(context, args); 714 | return result; 715 | }; 716 | }; 717 | 718 | // Returns a function that will be executed at most one time, no matter how 719 | // often you call it. Useful for lazy initialization. 720 | _.once = function(func) { 721 | var ran = false, memo; 722 | return function() { 723 | if (ran) return memo; 724 | ran = true; 725 | memo = func.apply(this, arguments); 726 | func = null; 727 | return memo; 728 | }; 729 | }; 730 | 731 | // Returns the first function passed as an argument to the second, 732 | // allowing you to adjust arguments, run code before and after, and 733 | // conditionally execute the original function. 734 | _.wrap = function(func, wrapper) { 735 | return function() { 736 | var args = [func]; 737 | push.apply(args, arguments); 738 | return wrapper.apply(this, args); 739 | }; 740 | }; 741 | 742 | // Returns a function that is the composition of a list of functions, each 743 | // consuming the return value of the function that follows. 744 | _.compose = function() { 745 | var funcs = arguments; 746 | return function() { 747 | var args = arguments; 748 | for (var i = funcs.length - 1; i >= 0; i--) { 749 | args = [funcs[i].apply(this, args)]; 750 | } 751 | return args[0]; 752 | }; 753 | }; 754 | 755 | // Returns a function that will only be executed after being called N times. 756 | _.after = function(times, func) { 757 | return function() { 758 | if (--times < 1) { 759 | return func.apply(this, arguments); 760 | } 761 | }; 762 | }; 763 | 764 | // Object Functions 765 | // ---------------- 766 | 767 | // Retrieve the names of an object's properties. 768 | // Delegates to **ECMAScript 5**'s native `Object.keys` 769 | _.keys = nativeKeys || function(obj) { 770 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); 771 | var keys = []; 772 | for (var key in obj) if (_.has(obj, key)) keys.push(key); 773 | return keys; 774 | }; 775 | 776 | // Retrieve the values of an object's properties. 777 | _.values = function(obj) { 778 | var keys = _.keys(obj); 779 | var length = keys.length; 780 | var values = new Array(length); 781 | for (var i = 0; i < length; i++) { 782 | values[i] = obj[keys[i]]; 783 | } 784 | return values; 785 | }; 786 | 787 | // Convert an object into a list of `[key, value]` pairs. 788 | _.pairs = function(obj) { 789 | var keys = _.keys(obj); 790 | var length = keys.length; 791 | var pairs = new Array(length); 792 | for (var i = 0; i < length; i++) { 793 | pairs[i] = [keys[i], obj[keys[i]]]; 794 | } 795 | return pairs; 796 | }; 797 | 798 | // Invert the keys and values of an object. The values must be serializable. 799 | _.invert = function(obj) { 800 | var result = {}; 801 | var keys = _.keys(obj); 802 | for (var i = 0, length = keys.length; i < length; i++) { 803 | result[obj[keys[i]]] = keys[i]; 804 | } 805 | return result; 806 | }; 807 | 808 | // Return a sorted list of the function names available on the object. 809 | // Aliased as `methods` 810 | _.functions = _.methods = function(obj) { 811 | var names = []; 812 | for (var key in obj) { 813 | if (_.isFunction(obj[key])) names.push(key); 814 | } 815 | return names.sort(); 816 | }; 817 | 818 | // Extend a given object with all the properties in passed-in object(s). 819 | _.extend = function(obj) { 820 | each(slice.call(arguments, 1), function(source) { 821 | if (source) { 822 | for (var prop in source) { 823 | obj[prop] = source[prop]; 824 | } 825 | } 826 | }); 827 | return obj; 828 | }; 829 | 830 | // Return a copy of the object only containing the whitelisted properties. 831 | _.pick = function(obj) { 832 | var copy = {}; 833 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 834 | each(keys, function(key) { 835 | if (key in obj) copy[key] = obj[key]; 836 | }); 837 | return copy; 838 | }; 839 | 840 | // Return a copy of the object without the blacklisted properties. 841 | _.omit = function(obj) { 842 | var copy = {}; 843 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 844 | for (var key in obj) { 845 | if (!_.contains(keys, key)) copy[key] = obj[key]; 846 | } 847 | return copy; 848 | }; 849 | 850 | // Fill in a given object with default properties. 851 | _.defaults = function(obj) { 852 | each(slice.call(arguments, 1), function(source) { 853 | if (source) { 854 | for (var prop in source) { 855 | if (obj[prop] === void 0) obj[prop] = source[prop]; 856 | } 857 | } 858 | }); 859 | return obj; 860 | }; 861 | 862 | // Create a (shallow-cloned) duplicate of an object. 863 | _.clone = function(obj) { 864 | if (!_.isObject(obj)) return obj; 865 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 866 | }; 867 | 868 | // Invokes interceptor with the obj, and then returns obj. 869 | // The primary purpose of this method is to "tap into" a method chain, in 870 | // order to perform operations on intermediate results within the chain. 871 | _.tap = function(obj, interceptor) { 872 | interceptor(obj); 873 | return obj; 874 | }; 875 | 876 | // Internal recursive comparison function for `isEqual`. 877 | var eq = function(a, b, aStack, bStack) { 878 | // Identical objects are equal. `0 === -0`, but they aren't identical. 879 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 880 | if (a === b) return a !== 0 || 1 / a == 1 / b; 881 | // A strict comparison is necessary because `null == undefined`. 882 | if (a == null || b == null) return a === b; 883 | // Unwrap any wrapped objects. 884 | if (a instanceof _) a = a._wrapped; 885 | if (b instanceof _) b = b._wrapped; 886 | // Compare `[[Class]]` names. 887 | var className = toString.call(a); 888 | if (className != toString.call(b)) return false; 889 | switch (className) { 890 | // Strings, numbers, dates, and booleans are compared by value. 891 | case '[object String]': 892 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 893 | // equivalent to `new String("5")`. 894 | return a == String(b); 895 | case '[object Number]': 896 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 897 | // other numeric values. 898 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 899 | case '[object Date]': 900 | case '[object Boolean]': 901 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 902 | // millisecond representations. Note that invalid dates with millisecond representations 903 | // of `NaN` are not equivalent. 904 | return +a == +b; 905 | // RegExps are compared by their source patterns and flags. 906 | case '[object RegExp]': 907 | return a.source == b.source && 908 | a.global == b.global && 909 | a.multiline == b.multiline && 910 | a.ignoreCase == b.ignoreCase; 911 | } 912 | if (typeof a != 'object' || typeof b != 'object') return false; 913 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 914 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 915 | var length = aStack.length; 916 | while (length--) { 917 | // Linear search. Performance is inversely proportional to the number of 918 | // unique nested structures. 919 | if (aStack[length] == a) return bStack[length] == b; 920 | } 921 | // Objects with different constructors are not equivalent, but `Object`s 922 | // from different frames are. 923 | var aCtor = a.constructor, bCtor = b.constructor; 924 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && 925 | _.isFunction(bCtor) && (bCtor instanceof bCtor))) { 926 | return false; 927 | } 928 | // Add the first object to the stack of traversed objects. 929 | aStack.push(a); 930 | bStack.push(b); 931 | var size = 0, result = true; 932 | // Recursively compare objects and arrays. 933 | if (className == '[object Array]') { 934 | // Compare array lengths to determine if a deep comparison is necessary. 935 | size = a.length; 936 | result = size == b.length; 937 | if (result) { 938 | // Deep compare the contents, ignoring non-numeric properties. 939 | while (size--) { 940 | if (!(result = eq(a[size], b[size], aStack, bStack))) break; 941 | } 942 | } 943 | } else { 944 | // Deep compare objects. 945 | for (var key in a) { 946 | if (_.has(a, key)) { 947 | // Count the expected number of properties. 948 | size++; 949 | // Deep compare each member. 950 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; 951 | } 952 | } 953 | // Ensure that both objects contain the same number of properties. 954 | if (result) { 955 | for (key in b) { 956 | if (_.has(b, key) && !(size--)) break; 957 | } 958 | result = !size; 959 | } 960 | } 961 | // Remove the first object from the stack of traversed objects. 962 | aStack.pop(); 963 | bStack.pop(); 964 | return result; 965 | }; 966 | 967 | // Perform a deep comparison to check if two objects are equal. 968 | _.isEqual = function(a, b) { 969 | return eq(a, b, [], []); 970 | }; 971 | 972 | // Is a given array, string, or object empty? 973 | // An "empty" object has no enumerable own-properties. 974 | _.isEmpty = function(obj) { 975 | if (obj == null) return true; 976 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 977 | for (var key in obj) if (_.has(obj, key)) return false; 978 | return true; 979 | }; 980 | 981 | // Is a given value a DOM element? 982 | _.isElement = function(obj) { 983 | return !!(obj && obj.nodeType === 1); 984 | }; 985 | 986 | // Is a given value an array? 987 | // Delegates to ECMA5's native Array.isArray 988 | _.isArray = nativeIsArray || function(obj) { 989 | return toString.call(obj) == '[object Array]'; 990 | }; 991 | 992 | // Is a given variable an object? 993 | _.isObject = function(obj) { 994 | return obj === Object(obj); 995 | }; 996 | 997 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. 998 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { 999 | _['is' + name] = function(obj) { 1000 | return toString.call(obj) == '[object ' + name + ']'; 1001 | }; 1002 | }); 1003 | 1004 | // Define a fallback version of the method in browsers (ahem, IE), where 1005 | // there isn't any inspectable "Arguments" type. 1006 | if (!_.isArguments(arguments)) { 1007 | _.isArguments = function(obj) { 1008 | return !!(obj && _.has(obj, 'callee')); 1009 | }; 1010 | } 1011 | 1012 | // Optimize `isFunction` if appropriate. 1013 | if (typeof (/./) !== 'function') { 1014 | _.isFunction = function(obj) { 1015 | return typeof obj === 'function'; 1016 | }; 1017 | } 1018 | 1019 | // Is a given object a finite number? 1020 | _.isFinite = function(obj) { 1021 | return isFinite(obj) && !isNaN(parseFloat(obj)); 1022 | }; 1023 | 1024 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). 1025 | _.isNaN = function(obj) { 1026 | return _.isNumber(obj) && obj != +obj; 1027 | }; 1028 | 1029 | // Is a given value a boolean? 1030 | _.isBoolean = function(obj) { 1031 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 1032 | }; 1033 | 1034 | // Is a given value equal to null? 1035 | _.isNull = function(obj) { 1036 | return obj === null; 1037 | }; 1038 | 1039 | // Is a given variable undefined? 1040 | _.isUndefined = function(obj) { 1041 | return obj === void 0; 1042 | }; 1043 | 1044 | // Shortcut function for checking if an object has a given property directly 1045 | // on itself (in other words, not on a prototype). 1046 | _.has = function(obj, key) { 1047 | return hasOwnProperty.call(obj, key); 1048 | }; 1049 | 1050 | // Utility Functions 1051 | // ----------------- 1052 | 1053 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 1054 | // previous owner. Returns a reference to the Underscore object. 1055 | _.noConflict = function() { 1056 | root._ = previousUnderscore; 1057 | return this; 1058 | }; 1059 | 1060 | // Keep the identity function around for default iterators. 1061 | _.identity = function(value) { 1062 | return value; 1063 | }; 1064 | 1065 | // Run a function **n** times. 1066 | _.times = function(n, iterator, context) { 1067 | var accum = Array(Math.max(0, n)); 1068 | for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); 1069 | return accum; 1070 | }; 1071 | 1072 | // Return a random integer between min and max (inclusive). 1073 | _.random = function(min, max) { 1074 | if (max == null) { 1075 | max = min; 1076 | min = 0; 1077 | } 1078 | return min + Math.floor(Math.random() * (max - min + 1)); 1079 | }; 1080 | 1081 | // List of HTML entities for escaping. 1082 | var entityMap = { 1083 | escape: { 1084 | '&': '&', 1085 | '<': '<', 1086 | '>': '>', 1087 | '"': '"', 1088 | "'": ''' 1089 | } 1090 | }; 1091 | entityMap.unescape = _.invert(entityMap.escape); 1092 | 1093 | // Regexes containing the keys and values listed immediately above. 1094 | var entityRegexes = { 1095 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), 1096 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') 1097 | }; 1098 | 1099 | // Functions for escaping and unescaping strings to/from HTML interpolation. 1100 | _.each(['escape', 'unescape'], function(method) { 1101 | _[method] = function(string) { 1102 | if (string == null) return ''; 1103 | return ('' + string).replace(entityRegexes[method], function(match) { 1104 | return entityMap[method][match]; 1105 | }); 1106 | }; 1107 | }); 1108 | 1109 | // If the value of the named `property` is a function then invoke it with the 1110 | // `object` as context; otherwise, return it. 1111 | _.result = function(object, property) { 1112 | if (object == null) return void 0; 1113 | var value = object[property]; 1114 | return _.isFunction(value) ? value.call(object) : value; 1115 | }; 1116 | 1117 | // Add your own custom functions to the Underscore object. 1118 | _.mixin = function(obj) { 1119 | each(_.functions(obj), function(name) { 1120 | var func = _[name] = obj[name]; 1121 | _.prototype[name] = function() { 1122 | var args = [this._wrapped]; 1123 | push.apply(args, arguments); 1124 | return result.call(this, func.apply(_, args)); 1125 | }; 1126 | }); 1127 | }; 1128 | 1129 | // Generate a unique integer id (unique within the entire client session). 1130 | // Useful for temporary DOM ids. 1131 | var idCounter = 0; 1132 | _.uniqueId = function(prefix) { 1133 | var id = ++idCounter + ''; 1134 | return prefix ? prefix + id : id; 1135 | }; 1136 | 1137 | // By default, Underscore uses ERB-style template delimiters, change the 1138 | // following template settings to use alternative delimiters. 1139 | _.templateSettings = { 1140 | evaluate : /<%([\s\S]+?)%>/g, 1141 | interpolate : /<%=([\s\S]+?)%>/g, 1142 | escape : /<%-([\s\S]+?)%>/g 1143 | }; 1144 | 1145 | // When customizing `templateSettings`, if you don't want to define an 1146 | // interpolation, evaluation or escaping regex, we need one that is 1147 | // guaranteed not to match. 1148 | var noMatch = /(.)^/; 1149 | 1150 | // Certain characters need to be escaped so that they can be put into a 1151 | // string literal. 1152 | var escapes = { 1153 | "'": "'", 1154 | '\\': '\\', 1155 | '\r': 'r', 1156 | '\n': 'n', 1157 | '\t': 't', 1158 | '\u2028': 'u2028', 1159 | '\u2029': 'u2029' 1160 | }; 1161 | 1162 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 1163 | 1164 | // JavaScript micro-templating, similar to John Resig's implementation. 1165 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 1166 | // and correctly escapes quotes within interpolated code. 1167 | _.template = function(text, data, settings) { 1168 | var render; 1169 | settings = _.defaults({}, settings, _.templateSettings); 1170 | 1171 | // Combine delimiters into one regular expression via alternation. 1172 | var matcher = new RegExp([ 1173 | (settings.escape || noMatch).source, 1174 | (settings.interpolate || noMatch).source, 1175 | (settings.evaluate || noMatch).source 1176 | ].join('|') + '|$', 'g'); 1177 | 1178 | // Compile the template source, escaping string literals appropriately. 1179 | var index = 0; 1180 | var source = "__p+='"; 1181 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 1182 | source += text.slice(index, offset) 1183 | .replace(escaper, function(match) { return '\\' + escapes[match]; }); 1184 | 1185 | if (escape) { 1186 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 1187 | } 1188 | if (interpolate) { 1189 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 1190 | } 1191 | if (evaluate) { 1192 | source += "';\n" + evaluate + "\n__p+='"; 1193 | } 1194 | index = offset + match.length; 1195 | return match; 1196 | }); 1197 | source += "';\n"; 1198 | 1199 | // If a variable is not specified, place data values in local scope. 1200 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 1201 | 1202 | source = "var __t,__p='',__j=Array.prototype.join," + 1203 | "print=function(){__p+=__j.call(arguments,'');};\n" + 1204 | source + "return __p;\n"; 1205 | 1206 | try { 1207 | render = new Function(settings.variable || 'obj', '_', source); 1208 | } catch (e) { 1209 | e.source = source; 1210 | throw e; 1211 | } 1212 | 1213 | if (data) return render(data, _); 1214 | var template = function(data) { 1215 | return render.call(this, data, _); 1216 | }; 1217 | 1218 | // Provide the compiled function source as a convenience for precompilation. 1219 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; 1220 | 1221 | return template; 1222 | }; 1223 | 1224 | // Add a "chain" function, which will delegate to the wrapper. 1225 | _.chain = function(obj) { 1226 | return _(obj).chain(); 1227 | }; 1228 | 1229 | // OOP 1230 | // --------------- 1231 | // If Underscore is called as a function, it returns a wrapped object that 1232 | // can be used OO-style. This wrapper holds altered versions of all the 1233 | // underscore functions. Wrapped objects may be chained. 1234 | 1235 | // Helper function to continue chaining intermediate results. 1236 | var result = function(obj) { 1237 | return this._chain ? _(obj).chain() : obj; 1238 | }; 1239 | 1240 | // Add all of the Underscore functions to the wrapper object. 1241 | _.mixin(_); 1242 | 1243 | // Add all mutator Array functions to the wrapper. 1244 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1245 | var method = ArrayProto[name]; 1246 | _.prototype[name] = function() { 1247 | var obj = this._wrapped; 1248 | method.apply(obj, arguments); 1249 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; 1250 | return result.call(this, obj); 1251 | }; 1252 | }); 1253 | 1254 | // Add all accessor Array functions to the wrapper. 1255 | each(['concat', 'join', 'slice'], function(name) { 1256 | var method = ArrayProto[name]; 1257 | _.prototype[name] = function() { 1258 | return result.call(this, method.apply(this._wrapped, arguments)); 1259 | }; 1260 | }); 1261 | 1262 | _.extend(_.prototype, { 1263 | 1264 | // Start chaining a wrapped Underscore object. 1265 | chain: function() { 1266 | this._chain = true; 1267 | return this; 1268 | }, 1269 | 1270 | // Extracts the result from a wrapped and chained object. 1271 | value: function() { 1272 | return this._wrapped; 1273 | } 1274 | 1275 | }); 1276 | 1277 | }).call(this); 1278 | --------------------------------------------------------------------------------