Proper use of JQuery with ember cli


#1

Hi,

I’m using ember cli to create my own app. And I need to use JQuery. When I use ('.className"), JSLint complaint that is not defined. There’re no problem when I run it though. But when I use this.$(’.className"). JSLint doesn’t complaint, but it doesn’t work at run time.

My question is how do I use JQuery properly so that JSLint doesn’t complaint and it works at run time too. Note that I only import ember in that class.


#2

You can either add "$": true to your .jshintrc file (within the "predef" section) or use Ember.$ instead.


#3

Ember. uses Ember's instance of the jQuery object, and you should pretty much always use that for performance reasons. The exception would be for views, where this. gives you the jQuery instance scoped to the current view. Another thing worth keeping in mind is almost everything jQuery does is “DOM aware”, which means if you’re reaching for it in a controller or route you might not be separating your concerns enough.


#4

Thanks @Panman8201 and @kylecoberly. I’m using Ember.$ now. I’m using it inside a view. I think I can create a view for the element I want to manipulate with JQuery and change the view instead of DOM directly, but it is overkill for a super simple html code (like 10 lines).

@kylecoberly Can you explain why it performs better if I use Ember.$? What are the differences between the Ember instance and the current view scoped jQuery instance?


#5

I may have misspoke on the performance gain between Ember. and - I thought the former used the same instance throughout and the latter used a new instance every time you made a call, but I was thinking of the issue with not caching selectors. Unless someone knows better than me, I think they’re identical but Ember.$ won’t need to be imported as a separate module or excused on .jshintrc as @Panman8201 suggested.

As far as Ember. vs. this., the biggest advantage is that you can query the view’s element with this.(). You can also do crazy (performant) selectors that you wouldn't normally do, like this.(“div”) because you’re dealing with such a narrow subset of the DOM. You can still use Ember. if, for some reason, you need to act on an element outside of the view, but 9/10 this.() is what you’re looking for.


#6

Thanks @kylecoberly for your explanation. I know why this.$() doesn’t work in my case. I’m querying an element outside of the view.


#7

You can

var $ = Ember.$;

to keep things simple.


#8

I’m pretty sure there’s a reason why they’ve aliased the top level $ I’d discourage this - although it definitely would work…