-1

I am using JQuery in a Module Pattern. I have a question about using JQuery Objects.

See the following example:

var myFeature = {

   'config' : {
        'container' : $('#myFeature'),

    'init' : function(config) {

        myFeature.config.container.css('display', 'none');

    }
}`

Why does the above example not work? What would be best practice when working with Jquery Objects in module pattern?

2 Answers2

2

Assuming that I've added the missing } in the right place (I also added a semicolon at the end, I don't recommend relying on the horror that is Automatic Semicolon Insertion):

var myFeature = {
    'config' : {
        'container' : $('#myFeature'),
    }
    'init' : function(config) {
        myFeature.config.container.css('display', 'none');
    }
};

...then the only reason I can see for why it wouldn't work would be if this code were executed before the element existed. So your container property ends up referring to a jQuery set with nothing in it, because as of when that property was initialized, there was no element with the id "myFeature".

The solution would be to initialize the container property at a time when you know the element exists, or to not use the container property at all since looking up an element by its id is very, very fast.

If the element is in the main markup of your page, make sure that the script tag that contains the code above is after that markup. The usual recommendation is to put the script tag(s) at the very end of your page, just before the closing </body> tag, so that all elements in the page's markup exist as of when the script code runs.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks you. You were right: the js-script was executed before the element was build. Putting the script at the end of the page solved the problem, but: – leo_vincere Nov 09 '14 at 15:10
  • How could be a good practice to organize my code then? I use to write the module patterns in a separate js-file and include it at the top of the page. Should I wrap the file in a document-ready? Do you have any suggestions? – leo_vincere Nov 09 '14 at 15:17
  • 1
    @leo_vincere: There's no need for a `ready` callback if you put the `script` tag at the end. – T.J. Crowder Nov 09 '14 at 15:33
1

See changes below:

var myFeature = {
    'config' : {
        'container' : $('#myFeature')  // 1: removed comma
    },                                 // 2: added comma and right curly brace
    'init' : function(config) {
        myFeature.config.container.css('display', 'none');
    }
};                                     // 3: added semi-colon
  1. the extra comma will sometimes cause errors in old versions of IE
  2. keys/value pairs are delimited by commas in hashes
  3. need semi-colon at end of statement. "need" is used loosely, but it's better safe than sorry
serv-inc
  • 35,772
  • 9
  • 166
  • 188
vol7ron
  • 40,809
  • 21
  • 119
  • 172