简体   繁体   中英

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?

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 .

Your problem is that this.$("#tags") searches for a DOM element with id: tags inside your components DOM element.

To solve your problem, you should use this.$().tagsInput({..}) instead.

Also see this JSBin for a working example.

Add setup jquery code into your component.js like following:

import Ember from 'ember';

export default Ember.Component.extend({

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

setupTagsInputPlugin: Ember.on('didRender', function() {
    this.$("#tags").tagsInput({
width:"100px"
    });
  }),

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM