简体   繁体   English

需要帮助编写干净有组织的javascript代码

[英]Need help writing clean organized javascript code

I am a newb with javascript and JQuery, so I am having a lot of trouble writing clean, organized code. 我是使用javascript和JQuery的新手,因此在编写干净,有组织的代码时遇到很多麻烦。 The code below just feels sloppy and I know it is. 下面的代码感觉很草率,我知道是的。 Here is a sample of what my code looks like. 这是我的代码的示例。 If anyone has suggestions or comments about how to improve it via functions, objects, classes, that would be awesome. 如果有人对如何通过函数,对象,类进行改进提出建议或意见,那将是很棒的。

The code below uses a datatable plugin, and generally would contain all the code for my page. 下面的代码使用一个datatable插件,通常包含我页面的所有代码。 There are still many more event handlers to write and such, but I would like to first get a handle on what I have already written before I get in too deep. 还有更多的事件处理程序要编写,诸如此类,但是我想先了解一下我已经编写的事件,然后再深入研究。

var plannerTable;


$(function () {

    // Initialize datatable object
    plannerTable = $('#plannerTable').dataTable
    ({
        "bJQueryUI": true,
        "bFilter": true,
        "sPaginationType": "full_numbers",
        "oLanguage":
            {
                "sZeroRecords": "Add some tasks to your planner"
            },
        "aoColumns":
            [
                { "bSortable": true, "bSearchable": false }, // task id
                {"bSortable": true, "bSearchable": false }, // course
                {"bSortable": false, "bSearchable": false }, // Edit 
                {"iDataSort": 2 }, // due date
                null,  // task
                {"bSortable": false, "bSearchable": false }, // Options     
                {"bSortable": false, "bSearchable": false} // Delete    
            ]
    });


    /* Insert Time Filter Controls into datatable */
    var filterHtml =  [
        '<ul id="plannerTable_TimeFilter" class="dataTables_TimeFilter">',
        '<li><a href="#">Day</a></li>',
        '<li><a href="#">Week</a></li>',
        '<li><a href="#">Month</a></li>',
        '<li><a href="#">All</a></li>',
        '<li><a href="#">Last 30 Days</a></li>',
        '</ul>'
    ]

    $('#plannerTable_filter').after(filterHtml.join(''));



    var dateFilters = $('#plannerTable_TimeFilter li');

    /* setup filter click event */
    dateFilters.click(function () 
    {
        var dateFilter = $(this).text().replace(/\s+/g, '');

        /* Get tasks by date range */
        $.getJSON('/Planner/Planner/GetTasksByDateRange', { 'dateFilter': dateFilter }, function (data) 
        {
            plannerTable.fnClearTable();

            $.each(data, function (key, value) 
            {
                var row = createTableRow(value);

                /* add row to table */
                plannerTable.fnAddTr($(row)[0], true);
            });
        });
    });


    /*
    * Function: createTableRow
    * Purpose:  Creates an HTML Row using the html in this function
    * Returns:  constructed html row
    * Inputs:   row data object
    */
    function createTableRow(value) 
    {

        var date = new Date(parseInt(value.DueDate.substr(6)));

        /* convert date to proper format */
        /* construct html row */
        var row = [
            '<tr>',
                '<td style="display: none;">' + value.TaskId + '</td>',
                '<td class="tag-bg" style="width: 10px;">',
                    '<span class="tag" style="background-color:' + value.CourseBackgroundColor + '" title="' + value.CoursePrefix + '">&nbsp;' + '</span>',
                    '<span style="display: none;">' + value.CoursePrefix + '</span>',
                '</td>',
                '<td class="edit">',
                    '<a href="#"><img src="../../../../Content/Images/Planner/edit-icon.png" /></a>',
                '</td>',
                '<td class="due-date">' + value.DueDate + '</td>',
                '<td class="task-col">' + value.TaskName + '</td>',
                '<td class="options">',
                    '<a class="desc" href="#"><img src="../../../../Content/Images/Planner/desc-off-icon.png" /></a>',
                    '<a class="alert" href="#"><img src="../../../../Content/Images/Planner/bell-off-icon.png" /></a>',
                '</td>',
                '<td class="delete">',
                    '<a href="#"><img src="../../../../Content/Images/Planner/delete-icon.png" /></a>',
                '</td>',
            '</tr>'
         ]

        return row.join('');
    }
});

There's one tip that will make your code a little cleaner, but also be more efficient in performance. 有一个技巧可以使您的代码更简洁,但也可以提高性能。 Don't create html in js using string concatenation. 不要使用字符串连接在js中创建html。 Use arrays. 使用数组。

var filterHtml = [
    '<ul id="plannerTable_TimeFilter" class="dataTables_TimeFilter">',
    '<li><a href="#">Day</a></li>',
    '<li><a href="#">Week</a></li>',
    '<li><a href="#">Month</a></li>',
    '<li><a href="#">All</a></li>',
    '<li><a href="#">Last 30 Days</a></li>',
    '</ul>'    
]
$('#plannerTable_filter').after(filterHtml.join(''));

You can use the same technique if you need to build out a list from a js array: 如果您需要从js数组构建列表,则可以使用相同的技术:

var data = [1,2,3,4,5,6],
    html = ['<ul>'];

for(var i=0,len=data.length; i<len; i++){
    html.push('<li>'+data[i]+'</li>');
}
html.push('</ul>');

$(target).html( html.join('') );  

Also, don't be afraid of vertical whitespace. 另外,不要担心垂直空格。 It helps break up the code so its not clumped together vertically. 它有助于分解代码,以免其垂直聚集在一起。

Add generous doses of comments too. 也添加大量的评论。 If you are using an editor that has code syntax highlighting, usually comments are in different colors than code. 如果您使用突出显示代码语法的编辑器,则注释通常使用与代码不同的颜色。 So not only are you helping yourself later on by continuously documenting what is going on in your code, you get the added benefit of color helping to make your code more understandable. 因此,您不仅可以在以后不断地记录代码中发生的事情来帮助自己,还可以获得颜色的额外好处,有助于使代码更易于理解。

I would agree with Luke. 我同意路加福音。 If you are writing out large amounts of html with your javascript, I would look into outputting JSON and using jQuery Templates, Mustache, or PURE. 如果您使用JavaScript编写大量的html,我会考虑输出JSON并使用jQuery模板,Mustache或PURE。

I am in the midst of trying to implement something like it in my current project which is turning out to be much more JS-based then I originally thought. 我正在尝试在当前项目中实现类似的东西,而事实证明,该项目比起我最初的想法更基于JS。 As so, outputting a bunch of HTML and having to perform DOM operations over and over has become performance inhibiting. 因此,输出一堆HTML并一遍又一遍地执行DOM操作已成为性能的障碍。

I would just google 'jQuery Best Practices' and 'jQuery Performance' -- You will find quite a few things regarding best practices with jQuery. 我只是用Google搜索“ jQuery最佳实践”和“ jQuery性能”-您会发现很多有关jQuery最佳实践的知识。

One thing I've learned over the years is to just continually program. 这些年来我学到的一件事就是不断编程。 I find myself getting caught up in what should be right instead of just doing what I want to do. 我发现自己陷入了应该做对的事情,而不仅仅是做我想做的事情。 Program. 程序。 I make sure that I test and build in benchmarks of my code where it is acceptable. 我确保在可接受的地方测试并建立代码基准。 From there, I just continually refactor as I find better and new ways to do things. 从那里开始,我不断地重构,因为我发现了更好的新方法来做事。

Good luck! 祝好运!

/* Insert Time Filter Controls into datatable */
var filterHtml = '<ul id="plannerTable_TimeFilter" class="dataTables_TimeFilter">' +
                '<li><a href="#">Day</a></li>' +
                '<li><a href="#">Week</a></li>' +
                '<li><a href="#">Month</a></li>' +
                '<li><a href="#">All</a></li>' +
                '<li><a href="#">Last 30 Days</a></li>' +
            '</ul>';
$('#plannerTable_filter').after(filterHtml);

into 进入

var timefiller = $("<ul></ul>").addClass("dataTables_TimeFilter");
$(["Day", "Week", "Month", "All", "Last 30 Days"]).each(function() {
   $("<a></a>").text(this).attr("href", "myhref").wrap("<li />").appendTo(timefiller);
});

THis is nothing you should use, it is just a way to use recursive stuff in a better way, so if you want to change the "a" into a "b" you dont have to do it 6 or nth times. 这不是您应该使用的东西,它只是一种以更好的方式使用递归内容的方法,因此,如果您想将“ a”更改为“ b”,则不必重复执行6次或n次。

But for your work i would suggest you highly jquery templ plugin, it´s beta, but it´s working as you need it, because something like this is for me personally a no-go. 但是对于您的工作,我建议您使用高度jQuery的templ插件,它是beta版,但可以根据需要运行,因为这样的事情对我个人而言是不行的。

var row = '<tr>' +
                      '<td style="display: none;">' + value.TaskId + '</td>' +
                      '<td class="tag-bg" style="width: 10px;">' +
                            '<span class="tag" style="background-color:' + value.CourseBackgroundColor + '" title="' + value.CoursePrefix + '">&nbsp;' + '</span>' +
                            '<span style="display: none;">' + value.CoursePrefix + '</span>' +
                      '</td>' +
                      '<td class="edit">' +
                            '<a href="#"><img src="../../../../Content/Images/Planner/edit-icon.png" /></a>' +
                      '</td>' +
                      '<td class="due-date">' + value.DueDate + '</td>' +
                      '<td class="task-col">' + value.TaskName + '</td>' +
                      '<td class="options">' +
                            '<a class="desc" href="#"><img src="../../../../Content/Images/Planner/desc-off-icon.png" /></a>' +
                            '<a class="alert" href="#"><img src="../../../../Content/Images/Planner/bell-off-icon.png" /></a>' +
                      '</td>' +
                      '<td class="delete">' +
                            '<a href="#"><img src="../../../../Content/Images/Planner/delete-icon.png" /></a>' +
                      '</td>' +
                    '</tr>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM