Encapsulate a piece of JS code into a method

Keywords: Programming JQuery

}).mouseout(function(){
    $("#plate-3hover").removeClass("plate-3after")
});

$("#plate-4").mouseenter(function() {
    $("#plate-4hover").addClass("plate-4after")
}).mouseout(function(){
    $("#plate-4hover").removeClass("plate-4after")
});

$("#plate-5").mouseenter(function() {
    $("#plate-5hover").addClass("plate-5after")
}).mouseout(function(){
    $("#plate-5hover").removeClass("plate-5after")
});

$("#plate-6").mouseenter(function() {
    $("#plate-6hover").addClass("plate-6after")
}).mouseout(function(){
    $("#plate-6hover").removeClass("plate-6after")
});

$("#plate-7").mouseenter(function() {
    $("#plate-7hover").addClass("plate-7after")
}).mouseout(function(){
    $("#plate-7hover").removeClass("plate-7after")
});

As shown above, younger brother wants to encapsulate the above JS code into a JS method.But there is no way to think about it. I don't know how to do it. Please give us a pointer.It's best to have examples.

Note: This JS code is a special effect code, the effect is the animation effect of the mouse moving in and out.The principle is to remove the class style from the dom

10 answers



Given the lack of programming experience of the landlord, I won't say anything about packaging as a jQuery plug-in.In terms of packaging methods alone.

The method is the function.Is an initial means of code reuse for procedural languages, in short, is to encapsulate duplicate parts with functions.

For example, if a cat crows many times, cat.meow(), you will never be able to write code for the corresponding number of times, which is usually written as:

function meow(num){
    for(var i=0;i<num;i++){
        cat.meow()
    }
}

meow(1000)

This is the most basic form of code reuse.
Of course, an object-oriented language might have a simpler cat.meow(1000)

Then, for the owner of the building.Step by step, describe the methods at all levels.The simplest way to encapsulate a function is to:

function effect(srcDom,destDom,className){
    $(srcDom).mouseenter(function(){
        $(destDom).addClass(className)
    }).mouseout(function(){
        $(destDom).removeClass(className)
    })
}

Then call

effect('#plate-1','#plate-1hover','plate-1after')
effect('#plate-2','#plate-2hover','plate-2after')
effect('#plate-3','#plate-3hover','plate-3after')

Given that the ID and Class naming of the owner's DOM are quite regular, it can be written as follows

function effect(name){
    $('#'+name).mouseenter(function(){
        $('#'+name+'hover').addClass(name+'after')
    }).mouseout(function(){
        $('#'+name+'hover').removeClass(name+'after')
    })
}

Then call

effect('plate-1')
effect('plate-2')
effect('plate-3')

But this is not enough, the landlord should look at the event related to the knowledge of event delegation

Event Delegation

Event delegates are viewed in conjunction with a specific DOM structure.Suppose there is a structure like this:

<div class="wrap">
    <div class="box1">
        <span class="trigger">trigger</span>
        <div class="effect"></div>
    </div>
    <div class="box2">
        <span class="trigger">trigger</span>
        <div class="effect"></div>
    </div>
    <div class="box3">
        <span class="trigger">trigger</span>
        <div class="effect"></div>
    </div>
</div>
function effect(node){
    $(node).on('mouseenter','.trigger',function(){
        var $this=$(this);
        $this.parent().find('.effect').addClass('after')
    })
    $(node).on('mouseout','.trigger',function(){
        var $this=$(this);
        $this.parent().find('.effect').removeClass('after')
    })
}

This way, the call only needs to be made once.

effect('.wrap')

Of course, the assumption here is that each set of controls works similarly. If they are different, there are two solutions: 1. Use the box parent class to solve from a style level.2.js level with an additional configuration item parameter




That's what you think:

function addEvent(selector,n){
    for (var i=1;i<=n;i++){
        (function(){
                $(selector +"-"+i).mouseenter(function() {
                    $(selector +"-"+i+"hover").addClass(selector +"-"+i+"after")
                }).mouseout(function(){
                    $(selector +"-"+i+"hover").removeClass(selector +"-"+i+"after")
                });
            }
        })(i);        
}

addEvent('#plate',7);

The idea is to loop through all the elements that bind events and add the appropriate events to them.Note that closures are used in each loop to ensure that i is pointing correctly.
However, this is not recommended because many events will be bound if there are many plate elements.

Suggest an event proxy approach:

$(document).on('mouseover',function(e){
    if ($(e.target).hasClass('plate')){
        //Add a class to the platform that the mouse moved in
        //For example: $("#plate-"+$(e.target).index()+"hover").addClass("#plate-"+$(e.target).index()+"after")
    }
});
$(document).on('mouseout',function(e){
    if ($(e.target).removeClass('plate')){
        //Remove class for plate removed by mouse
    }
});

This way, you only need to bind two event handlers.
When triggered, determine if the mouse has moved into the target block (as you do not know your dom structure, this is not detailed here).It is suggested to add a uniform class for them to facilitate judgment.Of course, here the event should be bound to the parent element of the platform element, not the document, to reduce the triggering of unnecessary events
The triggered dom can then be selected through $(e.target) and the corresponding class is added.

Note here the differences between mouseenter and mouseover, mouseleave and mouseout.


* Comments support partial Markdown syntax: **bold** _italic_[link] (http://example.com) >Reference `code` - list.
Users you @ will also be notified




Suggest pasting DOMS together






* Comments support partial Markdown syntax: **bold** _italic_[link] (http://example.com) >Reference `code` - list.
Users you @ will also be notified


Provide ideas:

for (var i = 1; i <= 6; i++) {
    (function(j) {
        $("#plate-" + j).mouseenter(function() {
            $("#plate-" + j + "hover").addClass("#plate-" + j + "after")
        }).mouseout(function() {
            $("#plate-" + j + "hover").removeClass("#plate-" + j + "after")
        });
    })(i)
}









Light packaging (process oriented):

function f( ele ) {
    //The first is the dom element to operate on
    
    $(ele).mouseenter(function() {
        $(ele+"hover").addClass(ele+"after")
    }).mouseout(function(){
        $(ele+"hover").removeClass(ele+"after")
    });
}
//Then bind the event with a loop

Deep encapsulation (object-oriented):

function Binde( ele, length ) {
    this.f = function( ele ) {
        $(ele).mouseenter(function() {
            $(ele+"hover").addClass(ele+"after")
        }).mouseout(function(){
            $(ele+"hover").removeClass(ele+"after")
        });
    };
    
    for( var i = 0; i < length; i ++ ) {
        this.f( ele + i );
    }
}







$("selector[id|='plate']").mouseenter(function(){

  $("#"+$(this).attr("id")+"hover").addClass("")
}).mouseout(function(){
  $("#"+$(this).attr('id')+"hover").removeClass("")
})

selector is your tag name, I don't know your tag
It can also be solved without encapsulation.

Posted by adders on Mon, 08 Jul 2019 11:12:28 -0700