Вопрос

  • 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();
});
Это было полезно?

Решение

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>

Другие советы

It won't work because at the time when you query the element, the element is not there yet, thus your query will return an empty jQuery selection. You can only query for elements when the DOM is ready.

what would work though is on of the following:

create the element outside $(document).ready(). note that you have to provide the full html or work with $(..).attr(x,y) and the likes.

Widget = {
    ele : $("<div id='ele'>"),
    ....
}

or you can query the element on widget initialization.

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

You can include script just before body end tag.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demo</title>
</head>
<body>
    <!-- my HTML -->

    <script src="../js/vendor/jquery-1.9.1.js"></script>
    <script src="../js/vendor/jquery-migrate-1.1.1.js"></script>
    <script src="../js/custom.js"></script>
</body>
</html>

DOM is ready (no need for $(document).ready):

   /*custom.js */
    var Widget = (function($){
        var _$element;

        return {
            init: function(){ 
                  _$element = $('#myElementId');
                  // TODO - element is available from now on
           };
        };
    }(jQuery));

    Widget.init();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top