๐Ÿ“œ โฌ†๏ธ โฌ‡๏ธ

Javascript and jQuery bikes

Once again, opening the code of colleagues and horrified, I decided to write this article. I hope it will be useful for someone, at the same time it will be easier for me for newbies to explain what is wrong with their code just by throwing a link to this article.
Certainly the number of such things is very, very large, so the article will limit only a few.

1. Constants in the code


This problem concerns not only javascript, but programming as a whole. Consider an example:
$elem.on('keydown', function(e) {
    if (e.keyCode == 27) {
        //...
    }
});

27? , โ€” ESC. , , , , , .
, ESC, , , KEY_ESC = 27

2.


(, , ..), - . (, ajax). :

var id = $(this).attr('id').substring(8);

โ€” 8. html ..
( ):

var last_id = $('#answer_pid' + id + ' li:first div').attr('id').substr(7);

, js .

:
<div class="comment" id="comment_123"></div>

var id = $(this).attr('id').substring("comment_".length);

( ), js html.

data-* ,
<div class="comment" data-id="123"></div>

:
var id = $(this).attr('data-id');


var id = $(this).data('id');

( attr data )

3. $.post


โ€” jquery ajax โ€” $.ajax. shorthand , $.get, $.load, $.post .. , ( , json, post ), $.ajax.
shorthand , :

:

1.
$.post(url, data, function(data) {
            data = $.parseJSON(data);
            //...
});

2. try catch
$.post(url, data, function(data) {
	    try {
                data = $.parseJSON(data);
            } catch (e) {
                return;
            }
            //...
});

3. , $.post dataType ( , success ).

$.post(url, data, function(data) {
    //...
}, 'json');


. - , 5 , , .
$.post , :
$.post(url, data, function(data) {
    //...
}, 'json').error(function() {
   ///
});


โ€” . โ€” , ajax , :

$.ajaxSetup({
    error: function() {
        //   ,   
    }
});


$.post. โ€” $.post ( dataType ). $.ajax. .

$.ajax({
    type: "POST"
    url: url,
    data: data,
    dataType: "json",
    success: function(data) {
        //
    },
    error: function() {
        //
    }
});


4.


(, ยซ ยป). :

$('.comment a.delete').click(function(){
    //
});


โ€” ( ). , ( ):

$('.comment a.delete').unbind('click').click(function() {
    //
});

: jQuery 1.7 on, , .
:

$('body').on('click', 'a.external', function(e) {
	//          external
});

, .
, . :

$('body').on('mousemove', selector, function() {
	//
});


5. Namespaced events


, namespaced events jQuery 1.2 โ€” ( ).
:

$('a').on('click', function() {
	// 1
});
$('a').on('click', function() {
	// 2
});

, . โ€” $('a').off('click') . namespaced events. :

$('a').on('click.namespace1', function() {
	// 1
});
$('a').on('click.namespace2', function() {
	// 2
});

$('a').off('click.namespace2');
namespaced events : docs.jquery.com/Namespaced_Events


, . .

')

Source: https://habr.com/ru/post/149237/


All Articles