jeudi 28 avril 2016

Shared JavaScript File with Different Definitions of a Function Call

I have a 300 line javascript file that sets up jQuery event handlers and other needed functions for a partial view that's used by multiple views within a ASP.NET MVC application. The event handlers handle 99% of everything identically regardless of which view is using the partial. This question is about that 1% difference.

Since JavaScript doesn't have interfaces is it safe to define a function to be called by one or more of the event handlers that processes the things that are different in a separate file that is loaded depending on which view is used? If not, what would be the best way to handle this situation? In other languages I'd use interfaces and/or abstract classes in this situation.

Example:

shared file

$(document).ready(function() {
    //shared variables here for methods
    $(document).on('click', '.selectable-table tbody tr', function() {
        //do shared actions
        mySpecificFunction();
        //finish shared actions (if necessary)
    });
});

Definition1.js

function mySpecificFunction() {
   //do stuff
}

Definition2.js

function mySpecificFunction() {
   //do other stuff
}

The views would load the appropriate scripts as such:

<script src="definitionX.js"</script>
<script src="sharedScript.js"></script>

The "signature" (term being used generously because javascript) of mySpecificFunction() would be the same for each definition, but something in my gut is telling me that this is bad practice. Is there a better/correct way to do this or a design pattern for this purpose?

Aucun commentaire:

Enregistrer un commentaire