Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + Module Pattern: When to declare/query elements?

  • Typically, you don't start querying the DOM until the $(document).ready().
  • In both of the options below, the Widget is declared (and the elements are queried) outside of the $(document).ready().
  • Is this OK? Can I initialize the jQuery elements (as long as I'm not manipulating anything), OUTSIDE of the ready handler?
  • Would it be better to put this whole Widget definition inside the $(document).ready()?
  • Should I wait until the Widget.init() to query the elements?
  • Note: I'm brand new to JS design patterns, so please note if I'm missing something

Option1

Widget = {
    ele : $('#ele'),
    init : function(){ ... }
};

$(document).ready(function(){
    Widget.init();
});

Option2

Widget = (function(){
    var privateEle = $('#privateEle');
    return {
        publicEle: $('#publicEle'),
        init: function(){ ... }
    };
}());

$(document).ready(function(){
    Widget.init();
});
like image 825
Michael Lewis Avatar asked Feb 17 '23 00:02

Michael Lewis


1 Answers

What I would do:

var Widget = (function(){
    var ele;

    function init(_ele){
        ele = _ele;
    };

    return {
        init: init
    };
})();

$(function(){
    Widget.init( $('#foo') );
});

If your script is loaded before jquery, you will not see an error "undefined is not a function". But, if you perform a query before domReady, you could get unexpected result, ele = []

EDIT: btw.. put your <script> tags before </body> NOT within <head></head>

like image 101
neiker Avatar answered Mar 04 '23 22:03

neiker