Skip to content

Instantly share code, notes, and snippets.

@yuvaltobias
Forked from jamis/behaviors.js
Created July 11, 2011 16:37
Show Gist options
  • Save yuvaltobias/1076236 to your computer and use it in GitHub Desktop.
Save yuvaltobias/1076236 to your computer and use it in GitHub Desktop.
Behavior-registration for UJS with jQuery
// An Unobtrusive Javascript (UJS) driver based on explicit behavior definitions. Just
// put a "data-behaviors" attribute on your view elements, and then assign callbacks
// for those named behaviors via $.Behaviors.add.
$.Behaviors = {
add: function(trigger, behavior, handler) {
$('[data-behaviors~=' + behavior + ']').live(trigger, handler);
}
};
@yuvaltobias
Copy link
Author

First attempt. works, but looks clunky even to me... It's probably not working in the "jQuery way".

@itsadok
Copy link

itsadok commented Jul 12, 2011

For jQuery, it's probably more appropriate to add it as a property on the jQuery object rather than a new global variable.

$.behaviors = { ...

Also, instead of passing this explicitly, the jQuery way would be to use Function.call to pass is implicitly.

handler.call(this, event)

Also, I don't see why you would return false from the event handler and break the chain. Better let the handler decide if it wants to break the chain.

return handler.call(this, event)

And if you're doing all of that, you might as well just put the handler as the second parameter to bind.

$(this).bind(trigger, handler)

@yuvaltobias
Copy link
Author

We're doing it live()
It doesn't make much sense to call it a behavior, and expect to call $.Behaviors.add(...) each time an element is added dynamically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment