JavaScript Code / Code Review Guidelines

  • I am working on a large site that has many custom ones (javascript for specific pages). There is one main.js and page-specific.js file. Is there a better approach that the following pattern can use?

  • How can I reuse multiple methods that use ajax?

  • I am currently assigning all onclick built-in events like onclick = "MYSITE.message.send ... is the best way? Creating multiple $ (" # button ") .click (function () {}); seems to work more ...

    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");  
                    }  
                }  
            });  
        }  
    }  
    

    }

+5
source share
4

jquery div

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

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

"contentId" "userId".

+2

-, onclick="" - . jQuery click() , , . HTML JS- . , .

JS, JS / . inline <script> , .

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.

+1

:

  • , "", , , . , , , , main.js .

  • ajax, , "".

  • If you can encode your purpose of onclick events, then DO NOT do them inline will save you a lot of work.

0
source

I would consider adding my custom functionality as a jquery plugin.

0
source

All Articles