Class methods using jQuery - preventing conflicts with $

Topics: General
Oct 31, 2012 at 12:28 PM

As classes are declared in the global scope, what is the best practice for using jQuery with the '$' alias? Or should I stick with 'jQuery'?

Oct 31, 2012 at 4:09 PM

I'm not sure I follow.  Classes are declared at the global scope, but I'm not sure how that conflicts with '$'.  They do create a '__extends' function, but I don't know of any '$' symbols that are created.

Nov 1, 2012 at 3:21 PM
Edited Nov 1, 2012 at 3:22 PM

Sorry Jon, that made a lot more sense in my head when I wrote it :)

If I have the a class in TypeScript:

class Greeter {
    constructor (element: HTMLElement) { 
        $('#h1').css({ color: 'Red' });

It will compile to the following JavaScript:

var Greeter = (function () {
    function Greeter(element) {
            color: 'Red'
    return Greeter;

Most of the time, we would encapsulated any code that uses $ like this:

(function ($) {

So my question is, is there a best practice way of ensuring that the use of $ in a TypeScript module/class is encapsulated? Or do we have to use 'jQuery' itself, or pass it in to the constructor?

Nov 6, 2012 at 6:50 PM

It is not currently possible in TypeScript to get the isolation from changes to the jQuery binding that the above examples provides.  However, in general, it should be very rare that this is actually important.  Why do you want to use the enacapsulation technique you described?  Note that jQuery provides a binding for $ already, and you can use that directly.

There is a feature we are considering to allow anonymous modules, which would allow your example to be written:

module {
  var $ = jQuery;
  class Foo {
    doIt() { return $('#h1'); }
Nov 7, 2012 at 8:55 AM

I think that jQuery is so widely used nowadays, that you can assume it is safe to use the $ without any precautions.

Dec 5, 2013 at 7:24 PM
Edited Dec 6, 2013 at 2:35 PM
Not if you're building a SharePoint 2013 WebPart with TypeScript client code. As one example.

(SharePoint 2013's AssetPickers.js defines $ for itself. Obnoxious!)