Skip to content

Instantly share code, notes, and snippets.

@mikegehard
Created May 20, 2011 15:08
Show Gist options
  • Save mikegehard/983110 to your computer and use it in GitHub Desktop.
Save mikegehard/983110 to your computer and use it in GitHub Desktop.
Javascript Pattern for Namespacing javascript
// This is a good pattern to namespace javascript.
// Passing in jQuery assures that $ in our functions always refers to jquery
// Also a good pattern to pass in event to handers as that is the default for jQuery
// in a handler the "this" refers to the DOM element that caused the element.
window.Hello = {};
(function($, namespace){
namespace.Bar = {};
// Use jQuery to add your methods.
$.extend(namespace.Bar, {
removeAssetHandler: function removeFooHandler(event) {
var $deleteLink = $(this);
$deleteLink.parents('.related_foo_container').find('.button').show();
$deleteLink.parents('.related_foo_container').find('input').val('');
$deleteLink.parents('.add_destination_container').html('');
event.preventDefault();
}
});
})(jQuery, Hello);
//Testing
// Use .call on the function to change what "this" points to
// you can also spy on e.preventDefault to make sure that the
// defaults get prevented
beforeEach(function() {
spec.loadFixture('related_foo_container_fixture.html');
});
var e = {preventDefault: function(){}};
var callFooHandler = function() {
Hello.Bar.removeFooHandler.call($("#delete")[0], e);
};
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment