Last Updated: September 09, 2019
·
2.521K
· geetotes

My favorite Javascript library functions

Sometimes you're walking down the street*, developing a backbone application, and you just stumble across a super-helpful function in a common javascript library it sweeps you off your feet!

Underscore's _.bind function is one of those.

http://underscorejs.org/#bind

_.bind is great because it allows you to pass in this as a context to the method you're binding to. For example, I use it when setting up JQueryUI stuff:
render: function(){
this.$('.date-pick').datepicker({ onClose: _bind(this.setDate, this});
}

Since I'm passing in the this context from my view (which will include this.model) when datepicker calls setDate, the function will have the correct context to set an attribute on the model. Freaking awesome!

But, lo.... forgive me Underscore, for I have strayed. There is another function that has become the apple of my eye -- the $.when() function in that harlot of a library, JQuery!

http://api.jquery.com/jQuery.when/

Often times, I have an app view that will render some sub-views. Then, I need to bind something to the DOM elements created by the sub view. Instead of messing around with _.defer (which I find kind of confusing), $.wait swoops in to save the day!

render: function(){
    $.when(this.collection.each(this.doSubViewRender)).then(this.bindStuffToSubViews);
 }

Amazing!

Stay tuned for my new book, 10 Ways to Spice Up Your Relationship With Javascript

*Walking and coding can be hazardous to your health. Please develop responsibly.

1 Response
Add your response

Excellent writer! Far more entertaining than the other blocks of code I usually meet on the internet.

over 1 year ago ·