Created
October 22, 2010 21:20
-
-
Save HenrikJoreteg/641397 to your computer and use it in GitHub Desktop.
Rather than creating some other util global, just extend underscore.js with any additional methods you want.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you don't use underscore.js, use it (http://documentcloud.github.com/underscore/) | |
// Then, use underscore's mixin method to extend it with all your other utility methods | |
// like so: | |
_.mixin({ | |
escapeHtml: function () { | |
return this.replace(/&/g,'&') | |
.replace(/>/g,'>') | |
.replace(/</g,'<') | |
.replace(/"/g,'"') | |
.replace(/'/g,'''); | |
}, | |
otherFunc: function () { | |
// etc, etc. | |
} | |
}); | |
// simple. but. handy. |
Yap, @krunkasaurus (lol, I love the name) is right, Underscore already has _.escape
and the edge version has _.unescape
too.
You can also use Lo-Dash, a drop-in replacement for Underscore delivering performance, bug fixes, and additional features to make a custom build and embed it directly in your project like (BonsaiJS)[http://bonsaijs.org/].
perfect! just what I was looking for. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an old post, but just an fyi that backbone uses underscore and has an escape feature. I checked the backbone source and it uses the escape function from underscore:
_.escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(///g,'/');
};
So this mixin is no longer needed.
Also what's this nonsense from @millermedeiros on not extending objects you don't own? I understand why its horrible to extend the native DOM, but libraries like underscore and jQuery were made to be extended. In your uncompressed javascript source files you actually place the additional plugins or "mixins" under to signify that they are additions. Even as a new developer on a project, it makes complete sense.