Function
bind (target, method, args*) Function public
Module: | @ember/runloop |
---|
Defined in packages/ember-metal/lib/run_loop.js:120
Available since v1.4.0
import { bind } from '@ember/runloop';
- 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
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: Ember.run.bind(this, this.setupEditor) }); }), didInsertElement() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: Ember.run.bind(this, this.setupEditor) }); } setupEditor(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } });
In this example, we use Ember.run.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.
© 2020 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://api.emberjs.com/ember/2.18/functions/@ember%2Frunloop/bind