jQuery lets us pass data to events. This lets us close context. Consider the following code: <html> <head> <title>jQ - Context</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript"> $.noConflict(); myObj = { value: 2, value2: 3 } jQuery(document).ready(function(){ jQuery("#looseContext").click(function(){ alert(myObj.value); }); jQuery("#closedContext").click({value: myObj.value, obj: myObj}, function(event){ alert(event.data.value); event.data.value *= 2;
//You can use this same logic to pass 'this' into a jQuery context scope. event.data.obj.value2 *= 3; }); jQuery("#looseContext2").click(function(){ //Every time #closedContext is clicked, myObj.value2 gets multiplied by 3. alert(myObj.value2); }); myObj.value = 4; }); </script> </head> <body id="body" onload=""> <button id="looseContext">Value of 4</button> <button id="closedContext">Multiples of 2</button> <button id="looseContext2"> Changing Value with multiples clicks </button>
</body> </html> |
jQuery >