Quiz

  1. Can you explain delegation in more detail?
    Event delegation and jQuery is really cool, but would love to know if there is an easy way to remember how it works .

    Great question! The key, I think, is inheritance and containment. Consider a map of the world. Suppose we click on Wellesley College.

    • Have we clicked on the town of Wellesley? Yes
    • Have we clicked on the Norfolk County? Yes
    • Have we clicked on the state of Massachusetts? Yes
    • Have we clicked on the USA? Yes
    • Have we clicked on North America? Yes
    • Have we clicked on the map? Yes

    Suppose each of those jurisdictions have something to say about the matter. (Maybe in the real world, there was a toxic waste spill. Maybe we need to notify all those jurisdictions.)

    Delegation says: rather than add a click handler to each of the small things (e.g. towns), let's add a click handler to a single big thing that contains all of the small things.

    The click handler on the container can know which small thing was clicked on by using this or event.target.

    
        $("container selector").on(
            'click',
            'small selector',
            function (evt) { handler(this); });
    
    

    (Those are usually the same, but if they aren't, you usually want this.)