joshuahornby10 joshuahornby10 - 3 months ago 26
jQuery Question

jQuery Plugin into Ember component

I am trying to turn this jQuery plugin https://github.com/xoxco/jQuery-Tags-Input into an Ember component.

import Ember from 'ember';

export default Ember.Component.extend({

tagName : "input",
type : "text",
attributeBindings : [ "name", "type", "value", "id"],

_initialize: function() {

Ember.assert("Tags Input has to exist on Ember.$.fn.tagsInput", typeof Ember.$.fn.tagsInput === "function");

this.$('#tags').tagsInput({'width':'100px'});

}.on('didInsertElement')
});


Then in my handlebar file
{{tag-input id="tags"}}


But it seems that the jQuery isn't working as it is just a standard input box. This is the generated HTML
<input id="tags" class="ember-view" type="text"></input>


But if I copy
this.$('#tags').tagsInput({'width':'100px'});
into the console and run it the element uses the plugin.

What would be the reason that the plugin wouldn't get fired on didInsertElement?

Answer

In addition to what kunerd said, you might need to schedule this to after everything is fully rendered by scheduling your code to the afterRender queue in the run loop, like this:

_initialize: function({
  Ember.run.scheduleOnce('afterRender', this, function() {
    this.$().tagsInput({'width': '100px'});
  });
}).on('didInsertElement')

Ember.run is a slightly complicated topic, but essentially things happen in order in "queues" that Ember fires off, and the afterRender queue is the one that happens after everything is rendered.

Here's a pretty good blogpost on Ember.run, and here's an even more in-depth book-like repository on it.