JavaScript 代码组织建议/代码审查

发布于 2024-09-11 11:32:43 字数 1327 浏览 10 评论 0原文

  1. 我正在一个大型网站上工作,该网站有很多自定义(页面特定的js)。有一个 main.js 和 page-specific.js 文件。有没有更好的方法可以使用以下模式?

  2. 如何重构使用 ajax 的多个方法?

  3. 我目前内联分配所有 onclick 事件,例如 onclick="MYSITE.message.send... - 有更好的方法吗?创建多个 $("#button")。 click(function() {}); 似乎需要更多工作......

    var MYSITE = MYSITE ?我的网站:{};
    var 我的网站{  
    书签:{
        添加:函数(contentId,userId){  
            变量数据 = {  
                内容ID:内容ID,  
                用户ID:用户ID  
            };  
            $.ajax({  
                网址:“/休息/书签/”,  
                类型:“帖子”,  
                数据:数据,  
                完成:功能(响应){  
                    如果(响应。错误){  
                        警报(响应。错误);  
                    } 别的 {  
                        警报(“成功”);  
                    }  
                }  
            });  
        }  
    },  
    信息: {  
        /* 书签 */  
        发送:函数(contentId,userId){  
            变量数据 = {  
                内容ID:内容ID,  
                用户ID:用户ID  
            };  
            $.ajax({  
                网址:“/休息/书签/”,  
                类型:“帖子”,  
                数据:数据,  
                完成:功能(响应){  
                    如果(响应。错误){  
                        警报(响应。错误);  
                    } 别的 {  
                        警报(“成功”);  
                    }  
                }  
            });  
        }  
    }  
    

    }

  1. I am working on a large site that has a lot of custom (page specific js). There is one main.js and page-specific.js files. Is there a better approach that can use the following pattern?

  2. How can I re-factor multiple methods that use ajax?

  3. I currently assign all onclick events inline such as onclick="MYSITE.message.send... - it there a better way? Creating multiple $("#button").click(function() {}); seems like more work...

    var MYSITE = MYSITE ? MYSITE: {};
    var MYSITE {  
    bookmark: {
        add: function(contentId, userId) {  
            var data = {  
                contentId: contentId,  
                userId: userId  
            };  
            $.ajax({  
                url: "/rest/bookmarks/",  
                type: "post",  
                data: data,  
                complete: function(response) {  
                    if (response.error) {  
                        alert(response.error);  
                    } else {  
                        alert("success");  
                    }  
                }  
            });  
        }  
    },  
    message: {  
        /* <a onclick="MYSITE.message.send('1234', '1234');" href="javascript:void(0);">BOOKMARK</a> */  
        send: function(contentId, userId) {  
            var data = {  
                contentId: contentId,  
                userId: userId  
            };  
            $.ajax({  
                url: "/rest/bookmarks/",  
                type: "post",  
                data: data,  
                complete: function(response) {  
                    if (response.error) {  
                        alert(response.error);  
                    } else {  
                        alert("success");  
                    }  
                }  
            });  
        }  
    }  
    

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

尽揽少女心 2024-09-18 11:32:43

您可以使用 jquery 委托方法
如果您有带有标签的 div 元素

<div id="bookmarks">
<a href="#">BOOKMARK</a>
</div>

$("div#bookmarks").delegate("a", "click", function(){
    MYSITE.message.send('1234', '1234');
});

,则可以动态获取“contentId”和“userId”。

You can use jquery delegate method
if you have div element with a tags

<div id="bookmarks">
<a href="#">BOOKMARK</a>
</div>

$("div#bookmarks").delegate("a", "click", function(){
    MYSITE.message.send('1234', '1234');
});

and you can get 'contentId' and 'userId' dynamically.

明媚殇 2024-09-18 11:32:43

首先,直接分配 onclick="" 是不好的做法。使用 jQuery 的 click() 方法并不需要做更多的工作,但即使是这样,它也更干净,更值得推荐。它将 HTML 标记与 JS 功能分开,并且使以后更容易更改内容。这是你应该重构的第一件事。

我对 JS 所做的就是创建一个包含所有类/核心功能的主库 JS 文件。然后,我在特定页面上使用内联

在全局 app.js 文件中,我将有一个函数:

function initLinksOnPageX() {
  $('#button').click(function() { MYSITE.message.send('1234', '1234'); });
  /* ... setup any other events ... */
}

在页面正文中:

<script type="text/javascript">
  $(initLinksOnPageX);
</script>

同样,这可以使您的标记远离任何 JS 代码,因此与 JS 相关的更新发生在一个文件(或更少)中。通过这种设置,您不应该严格需要特定于页面的 JS 文件,尽管从组织上来说这可能是有意义的——我不知道您的 JS 有多大。

Firstly, assigning onclick="" directly is bad practice. Using jQuery's click() method is not that much more work, but even if it was, it is cleaner and much more recommended. It keeps your HTML markup separate from your JS functionality and makes it easier to change things later on. That's the very first thing you should refactor.

What I do with my JS is create one main library JS file with all of my classes/core functionality. I then use inline <script> tags on specific pages to call the method that hooks up the links to the functions.

In the global app.js file, I'll have a function:

function initLinksOnPageX() {
  $('#button').click(function() { MYSITE.message.send('1234', '1234'); });
  /* ... setup any other events ... */
}

In the page body:

<script type="text/javascript">
  $(initLinksOnPageX);
</script>

Again, this keeps your markup clear of any JS code, so your JS related updates happen in one file (or fewer). With this setup you shouldn't strictly need page-specific JS files, though organizationally speaking it might make sense-- I don't know exactly how big your JS is.

尬尬 2024-09-18 11:32:43

我的想法:

  1. 这取决于许多因素,但如果页面特定代码“很大”,那么最好将其分开。然而,如果它只是几行,并且我们不是在谈论数千个页面,那么将其全部集中到 main.js 中可能不是一个大问题。

  2. 对ajax不是很熟悉,所以就转述如何“重构”。

  3. 如果您可以循环分配 onclick 事件,那么不内联执行它们将为您节省大量工作。

    如果您可以循环分配

My thoughts:

  1. This depends on many factors, but if the page specific code is "large" then it is probably best to keep it separate. If, however, it is just a few lines, and we are not talking about thousands of pages, then lumping it all into the main.js may not be a big issue.

  2. Not very familiar with ajax, so I will pass on commenting on how to "refactor".

  3. If you can loop your assignment of the onclick events, then NOT doing them inline is going to save you a lot of work.

晒暮凉 2024-09-18 11:32:43

我会考虑将我的自定义功能包装为 jquery 插件。

I'd consider wrapping my custom functionality up as a jquery plugin.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文