Function

Module: @ember/runloop

Available since v1.4.0

target
Object
target of method to call
method
Function|String
Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target.
args*
Object
Any additional arguments you wish to pass to the method.
returns
Function
returns a new function that will always have a particular context

Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronously integrate third-party libraries into your Ember application.

bind takes two main arguments, the desired context and the function to invoke in that context. Any additional arguments will be supplied as arguments to the function that is passed in.

Let's use the creation of a TinyMCE component as an example. Currently, TinyMCE provides a setup configuration option we can use to do some processing after the TinyMCE instance is initialized but before it is actually rendered. We can use that setup option to do some additional setup for our component. The component itself could look something like the following:

editor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import Component from '@ember/component';
import { on } from '@ember/object/evented';
import { bind } from '@ember/runloop';

export default Component.extend({
  initializeTinyMCE: on('didInsertElement', function() {
    tinymce.init({
      selector: '#' + this.$().prop('id'),
      setup: bind(this, this.setupEditor)
    });
  }),

  didInsertElement() {
    tinymce.init({
      selector: '#' + this.$().prop('id'),
      setup: bind(this, this.setupEditor)
    });
  }

  setupEditor(editor) {
    this.set('editor', editor);

    editor.on('change', function() {
      console.log('content changed!');
    });
  }
});

In this example, we use bind to bind the setupEditor method to the context of the RichTextEditor component and to have the invocation of that method be safely handled and executed by the Ember run loop.