binding - Attaching an event handler in JQuery. Direct-bound vs. Delegated -


i make single-page application. when hash changed, new elements loaded page via ajax.

i want set event handler new elements. there 2 ways.

  1. every event handlers delegated @ start.

    $("body").on(event, "element", handler)

  2. whenever hash changed, event handeler direct-bound new element. so, binding , removing handlers repeated.

    $("element").on(event, handler)

which performs better? (finding elements time vs. repeating bind-removal time) (sorry, english poor...)

it might have more information how single-page application works perhaps can consider these guidelines

  • how dynamic page? if it's static (doesn't change, may premature optimization)
  • how many dom elements involved here? more dom elements need wired individually, more work must done, more memory consumption, etc.
  • how nested dom elements? deeper nesting, means more bubbling of events.
  • in case of finding element id, lookup jquery's perspective extremely fast because dom element id names supposed unique , typically uses getelementbyid native method.
  • in case of finding elements tag, should have 1 body tag may have several hundred div tags if that's selecting.
  • when still unsure, it's time chrome developer tools involved further fine tune , diagnose potential performance problems may experience.
  • jquery's selector engine extremely powerful , flexible, not selectors perform same. can write gnarly selector overburdens browser unnecessarily.

in general, utilize event delegation when need large group of items behave given event.

i hope helpful.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -