Open In App

Backbone.js delegateEvents View

Backbone.js delegateEvents method provides us with a way to bind the elements with the specific HTML DOM. It also provides us with advantages over manually implementing jQuery to bind the events with the child elements during invocation of the render function. Every callback attached to it is bound to the view object. When we run delegate events with different events hash, callbacks are removed and delegated.

Syntax:



delegateEvents(events)

Parameters:

Example 1:






<!DOCTYPE html>
<html>
 
<head>
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
        type="text/javascript">
    </script>
</head>
 
<body style="background-color:black;">
    <h1 style="color:green;">GeeksforGeeks</h1>
    <div id="mydiv"></div>
    <script type="text/javascript">
        var delview = Backbone.View.extend({
            events: { 'click button': 'delegateFunc' },
            delegateFunc: function () {
                this.remove();
                window.alert("[delegate event]");
                document.write(
            "<h1 style='color:blue;'>GeeksforGeeks</h1>");
            },
 
            render: function () {
                this.$el.html(
            '<button>Invoke delegate event:</button>');
            },
            initialize: function () { this.render(); }
        });
        var object = new delview({ el: '#mydiv' });
        object.delegateEvents(); 
    </script>
</body>
 
</html>

Output:

 

Example 2:




<!DOCTYPE html>
<html>
 
<head>
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
 
</head>
 
<body style="background-color:black;">
    <h1 style="color:green;">GeeksforGeeks</h1>
    <div id="mydiv"></div>
    <script type="text/javascript">
        var delview = Backbone.View.extend({
            events: { 'click button': 'delegateFunc' },
            delegateFunc: function () {
                document.write(
"<p style='color:black;'>Example of delegate event</p>
"
                );
                document.write(
            "<h1 style='color:blue;'>GeeksforGeeks</h1>"
                );
            },
 
            render: function () {
                this.$el.html(
                '<button>Invoke delegate event:</button>'
                );
            },
            initialize: function () {
                document.write(
"<p style='color:white;'>Example of delegate event</p>
"
                );
                this.render();
            }
        });
        var object = new delview({ el: '#mydiv' });
        object.delegateEvents(); 
    </script>
</body>
 
</html>

Output:

 

Reference: https://backbonejs.org/#View-delegateEvents


Article Tags :