× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Using Ember.run.bind for external library callbacks

Alex Speller
Apr 18, 2016
<p>When using external javascript libraries with ember, there are often callbacks that you have to integrate with your ember app, for example:</p> <pre><code class="language-javascript">someLibrary.doSomething(function() { alert('it worked'); });</code></pre> <p>In ember, often you want to use the callback to call a method on an ember object, like this:</p> <pre><code class="language-javascript">someLibrary.doSomething(function() { myEmberObject.somethingWorked(); });</code></pre> <p>There's a problem here however - the callback is executing outside of Ember's runloop. C<span style="color:rgb(95, 99, 102)">allbacks that happen outside of the runloop cause something called an autorun. Ember detects that you did something to an Ember object outside of a runloop, and shedules one to happen automatically.</span> This can cause two problems.</p> <p>The first problem is a performance issue - autoruns are expensive so it's best to avoid them where possible.</p> <p>The second problem is that you will get test failures if this happens in test mode; Ember specifically warns you about this so that you know that it's happening and can fix it.</p> <p>There is a simple fix, to wrap the callback in a runloop:</p> <pre><code class="language-javascript">someLibrary.doSomething(function() { Ember.run(function() { myEmberObject.somethingWorked(); }); });</code></pre> <p>But now your code has gotten very verbose! Luckily, there's a simple shortcut provided by Ember:</p> <pre><code class="language-javascript">someLibrary.doSomething(Ember.run.bind(myEmberObject, 'somethingWorked'))</code></pre> <p>This code is equivalent to the previous snippet, but much shorter. The first argument is the object that will be the context (i.e. the value of 'this', the second argument is the method of that object that will be called.</p> <p>This quick shortcut can save a few lines in your callbacks and ensure your integrations with external libraries is correct!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus