jQuery and “Organized Code”

后端 未结 8 1782
星月不相逢
星月不相逢 2020-12-12 11:52

I\'ve been struggling lately with understanding the best way to organize jQuery code. I asked another question earlier and I don\'t think I was specific enough (found in thi

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 12:11

    In my opinion the method described by BaileyP is what I use to start off with then I normally abstract everything into more re-usable chunks, especially when some functionality expands to the point where it's easier to abstract it into a plugin then have it specific to one site.

    As long as you keep the large blocks of code in a seperate file and coded nicely you can then end up with some really clean syntax.

    // Page specific code
    jQuery(function() {
        for(var i = 0; i < 5; i++) {
             $("").bindWithServer("#inputContainer");
        }
    });
    
    // Nicely abstracted code
    jQuery.fn.bindWithServer = function(container) {
         this.change(function() {
                 jQuery.ajax({
                     url: 'http://example.com/',
                     success: function() { jQuery(container).unbindChildren(); }
                 });
         });
    }
    jQuery.fn.unbindChildren = function() {
        this.children().each(function() {
            jQuery(this).unbind().change(function() {});
        });
    }
    

提交回复
热议问题