Skip to content

Instantly share code, notes, and snippets.

@moos
Created March 18, 2014 22:59
Show Gist options
  • Save moos/9631625 to your computer and use it in GitHub Desktop.
Save moos/9631625 to your computer and use it in GitHub Desktop.
A handy method for Backbone views to execute an update method on requestAnimationFrame, eg. this.requestFrame('render');
/**
* Execute a Backbone View method or function at next animation frame, while
* correctly handling multiple requests.
*
* Caveat: only one anonymous function can be used at a time. Use a named function or method name.
*
* @example (from a Backbone view):
*
* this.requestFrame('render') // execute method render of current object
* this.requestFrame(this.render) // same as above
* this.requestFrame(function blah(){}, this) // execute immediate named function in 'this' context
*
* IE8, IE9: require a good requestAnimationFrame shim, eg, https://gist.github.com/paulirish/1579671
* Inspiration: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
*
* MIT License
*/
!function(){
_.extend(Backbone.View.prototype, {
__frameTicks : {},
/**
* @param fn {string|function} - method name in current class to execute or a function
* @param [context=this] {object} - context in which to execute fn
* @param args... - additional arguments to pass to method
* @return {number} request id
*/
requestFrame: function(fn, context /*, args */ ){
var
handler = fn,
name = _.isString(fn) ? (handler = this[fn], fn)
: fn && fn.name ? fn.name
: '__anonymous_fn__',
ticks = this.__frameTicks,
args = _(arguments).rest(2), // drop first two
self = this;
// return if already requested
if (name in ticks && ticks[name]) return;
return ticks[ name ] = window.requestAnimationFrame(function(){
// reset ticking flag
delete ticks[ name ];
// execute function
handler.apply(context || self, args);
});
}
});
)();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment