开发者

Refactoring Javascript

开发者 https://www.devze.com 2022-12-15 03:55 出处:网络
I have a lot of code in the admin area of my site that is, basically just CRUD operations using AJAX posting.

I have a lot of code in the admin area of my site that is, basically just CRUD operations using AJAX posting.

I was wondering if you had any tips on refactoring these type of functions either into generic functions or classes etc.

Here is some sample code, though a lot of this is duplicated in other functions with just different ajax parameters:

function BindAddMenuHeaderOption() {
    $("#AddMenuHeaderOption").click(function (e) {
        e.preventDefault();

        var headerOptionId = jQuery.trim($("#HeaderOptions").val());
        var menuHeaderId = jQuery.trim($("#MenuHeaderId").val());

        $.ajax(
        {
            type: "POST",
            url: "/Menu/AddMenuHeaderOption",
            data: "menuHeaderId=" + menuHeaderId + "&headerOptionId=" + headerOp开发者_如何学CtionId,
            dataType: "html",
            success: function (result) {
                var domElement = $(result);
                $("#ModalContent").empty();
                $("#ModalContent").append(domElement);
                BindAllBehaviours();
            }
        });
    });

}

function BindAddMenuItem() {
    $(".AddMenuItem").click(function (e) {
        e.preventDefault();

        //get header id from link by removing addmenuitem from this.id
        var currentId = $(this).attr("id").replace("AddMenuItem", "");

        //get itemnumber, itemname, itemdetails from textboxes with same header id
        var restaurantId = jQuery.trim($("#RestaurantId").val());
        var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
        var itemName = jQuery.trim($("#ItemName" + currentId).val());
        var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());

        $.ajax(
        {
            type: "POST",
            url: "/Menu/AddMenuItem",
            data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails,
            dataType: "html",
            success: function (result) {
                var domElement = $(result);
                $("#MenuContainer").replaceWith(domElement);
                var newNum = parseInt(itemNumber) + 1;
                $("#ItemNumber" + currentId).val(newNum);
                BindAllBehaviours();
            }
        });
    });

}

function BindUpdateMenuItem() {
    $(".UpdateMenuItem").click(function (e) {
        e.preventDefault();


        var restaurantId = jQuery.trim($("#RestaurantId").val());
        var itemNumber = jQuery.trim($("#UpdateItemNumber").val());
        var itemName = jQuery.trim($("#UpdateItemName").val());
        var itemDetails = jQuery.trim($("#UpdateItemDetails").val());

        var vars = GetHtmlParameters($(this));

        $.ajax(
        {
            type: "POST",
            url: "/Menu/UpdateMenuItem",
            data: "reastaurantId=" + restaurantId + "&menuItemId=" + vars["menuItemId"] + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails,
            dataType: "html",
            success: function (result) {
                var domElement = $(result);
                $("#MenuContainer").replaceWith(domElement);
                BindAllBehaviours();
            }
        });
    });

}


Minor nit: Constructing URL arguments should generally be done by a method rather than with concatenation because then you can ensure that you are URL-escaping the values correctly. Example: if 'restaurantId' contained an ampersand (&) character, then your data= variable would be corrupted. So, I suggest refactoring this into a dict ({restaurantId: restaurantId, ...}) or passing it to a method (something like: buildQueryArguments(name1, value1, name2, value2, ...)). Depending on your implementation, that method could be implemented to extract the values from the form fields directly.

However, your best bet is probably to use something like the jQuery Form Plugin (http://jquery.malsup.com/form/) because this will give your users a better user experience in case they don't have full JS support.

Otherwise, there are some cheap refactorings you can do (encapsulate the .ajax() call with something that fill sin default args, for example), but it isn't going to make much of a difference for you in the long run.


Since all of this code involves submitting groups of INPUT elements using AJAX, you could try putting them in FORM elements (if you haven't already) and using the jQuery Form Plugin to upgrade them to AJAX. This also gives you fallback behavior if Javascript is disabled for whatever reason.


You could break up the .ajax callbacks into smaller functions by using the higher level jQuery.post( url, [data], [callback], [type] ).


I cant see any good way of refactoring this. You may be able to save a few lines of code by packing it into one function, but it would become less easy to understand.

Remember Refactoring is all about reducing the lines of code as long as the code is still readable and understandable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号