jQuery Event $.proxy() Method



The jQuery event $.proxy() method allows you to create a new function with a specific context (i.e., its value). This is useful for binding an event handler to an element where the context needs to point back to a different object.

The $.proxy() method was deprecated in jQuery version 3.3.

Syntax

Following is the syntax of the jQuery event $.proxy(() method −

$(selector).proxy(function, context)

Parameters

The method accepts two parameters named 'function' and 'context'. These parameters are described below −

  • function − The existing function whose context will be changed.
  • context − An object to which the context of the function should be set.

Return Value

This method does not return any value.

Example 1

The following is the basic example of the jQuery event $.proxy() method −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below button to set the context of the details function inside studentDetails.</p>
    <button>Click me</button>
    <br><br>
    <span></span>
    <script>
        var studentDetails = {
            details: function() {
                $('span').text("Student details: Name, age, city, etc.");
            }}
            $("button").click($.proxy(studentDetails, "details"));
    </script>
</body>
</html>

Output

After executing the above program, a button is displayed. When clicked, it sets the context of the 'details' function within the 'studentDetails' object −


Example 2

Following is another example of the jQuery event $.proxy(() method. We use this method to change the context of a function to a specific object −

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <p>The pop-up alert "Hello TutorialsPoint" will appear on the browser screen every 2 seconds.</p>
    <script>
        var obj = {
            name: "TutorialsPoint",
            sayHello: function(){
                alert("Hello " + this.name);
            }
        };
        //setInterval(obj.sayHello, 2000); it will display only "Hello" + undefined.
        setInterval($.proxy(obj.sayHello, obj), 2000);
    </script>
</body>
</html>

Output

The program above displays a pop-up alert with the specified content every two seconds −


jquery_ref_events.htm
Advertisements