- Jquery Provides Proxy Mechanism through $.proxy() method.
- Proxy mechanism is really helpful where we need some delegate to represent the functionality.
- Generic use case of a proxy mechanism is the way of binding different context to a method through a proxy wrapper.
- In this Demo, “We will create method to change color of the text and expose it with a proxy for different context“.
- In this example we have ,
—A method called ‘chageColor()‘ inside a EVENT_SCRIPT object.
—This method is wrapped around by jquery proxy object and exposed by ‘proxyChangeColor‘ variable.
—‘proxyChangeColor‘ is then binded with two different contexts of student container and fruit container.
- The markup used for this demo is as below,
<ul class='student-container'>
<li>Sandeep1</li>
<li>Sandeep2</li>
<li>Sandeep3</li>
</ul>
<span class='fruit-container'>
<span>Mango</span>
<span>Apple</span>
<span>Orange</span>
</span>
var EVENT_SCRIPT = {
/*Changes the color*/
changeColor: function (event) {
var currentElement = event.target;
$(currentElement).css('color', 'red');
}
},
proxyChangeColor = $.proxy(EVENT_SCRIPT.changeColor, EVENT_SCRIPT);
$('.student-container li').on('click', proxyChangeColor);
$('.fruit-container span').on('click', proxyChangeColor);