2013-03-15 24 views
0

我卻高興不起來使用javascript我有我的一個項目的混亂,所以我決定把下面的插件結構的一切。請注意,我是一名C#開發人員,不會用jQuery做太多事情,但它看起來很有趣。在插件結構中封裝站點範圍的jquery事件和方法有什麼問題嗎?

(function($) { 

var methods = { 
    init: function(options) { 

     if (!cookiesEnabled()) { 
      window.location = "http://www.mysite.com/error?msg=nocookies"; 
     } 
     // autosize middle frame if right side has no content 
     autosizeframes('#right-side'); 

     // EVENTS 
     $(document).on('submit', '#signin_form', function (event) { 
      event.preventDefault(); 
      postAjaxForm($(this)); 

     }); 

     $(document).on('submit', '#register_form', function (event) { 
      event.preventDefault(); 
      postAjaxForm($(this)); 

     }); 

     $(document).on('click', '.user-settings', function (e) { 
      var menu = $(this).parent().children('#menu'); 
      if ($(menu).is(':visible')) { 
       $(menu).slideUp(500); 
      } else { 
       $(menu).slideDown(500); 
      } 
     }); 
    } 

}; 
// METHODS Commonly Used 
var postAjaxForm = function(form) { 
    var updateElement = $(form).attr('UpdateElement'); 

    if (!$(updateElement).length) { 
     alert('Unable to find update element'); 
     return false; 
    } 

    if ($(form).valid()) { 
     $.ajax({ 
      type: $(form).attr('method'), 
      url: $(form).attr('action'), 
      data: $(form).serialize(), 
      success: function(response) { 
       $(updateElement).html(response); 
       $.validator.unobtrusive.parse($(updateElement).find('form')); 
      }, 
      error: function(xhr,stats,errorMessage) { 

      } 
     }); 
    } 
    return true; 
}; 

var checkLength = function(element) { 
    if ($.trim(element).length) { 
     return true; 
    } 
    return false; 
}; 
var autosizeframes = function(element) { 
    if (!$.trim($(element).len)) { 
     $('#middle').width($('#middle').width() + $(element).width()); 
    } 
}; 

var cookiesEnabled = function() { 
    var enabled = (navigator.cookieEnabled) ? true : false; 
    if (typeof navigator.enabled == "undefined" && !enabled) { 
     document.cookie = "_test"; 
     enabled = (document.cookie.indexOf("_test") != -1) ? true : false; 
    } 
    return enabled; 
}; 

$.fn.site = function(method) { 
    if (methods[method]) { 
     return methods[method].apply(this,Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method == 'object' || !method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method' + method + ' Does not exist'); 
    } 
}; 
})(jQuery); 

輸入讚賞和感謝

回答

0

恕我直言,它纔有意義把東西到jQuery插件,如果他們的通用效用。

如果你的方法是具體到某個網站,你會只是包裝他們自己的命名空間和/或對象,而不是將它們拖放到jQuery的命名空間更好。

因此,它可能是有意義的你cookiesEnabled功能添加到$(注:不$.fn),但我不認爲你的$.fn.site有道理。

特別地,在$.fn功能都應該適用於集合元素,如封裝在現有jQuery對象,其中該對象被傳遞給函數作爲this。你methods.init功能通過$.fn.site暴露沒有做任何的。

+0

所以基本上,因爲我沒有做任何事情,在傳遞給init等的元素的元素或集合/ ..它會更好,只是包裝他們在一個簡單的關閉和具有內 2013-03-15 03:04:03

+0

其他方法是專用的,不弄亂$ .fn – 2013-03-15 03:07:10