3197891abd2c7abb0c8381c7f3b5de282a415e58

Using Jquery Proxy Mechanism

  • 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>
  • The jquery code for the proxy binding is as below
  • 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);
  • The output of the code is present the below fiddle:-
  • [フレーム]

    Sandeep
    Using Nth Child Selector in CSS And Jquery JavaScript Array Methods Example
    Sandeep

    A passionate Blogger and Developer.Love to code for web application using JavaScript.At present I am exploring the Web Component Specification.

    12 years ago jquery 774

    AltStyle によって変換されたページ (->オリジナル) /