Newbie
Newbie

Reputation: 1531

Two JS functions with Same name in single HTML

I'm having a function. In which data get value from getValue() function.

Below code is a fragment.

grid.js

function gridLoadComplete(){
    var data = getValue();      
}

Consider below HTML's

I have added grid.js fragment to staffGrid.html & teacherGrid.html.

When i load index.html it get's error. I don't get value in data because it's called twice.

Is there any way to resolve this problem. using the same function name getvalue() ??


Upvotes: 0

Views: 118

Answers (2)

plalx
plalx

Reputation: 43718

Looks like your issue rises from the fact that you have too many globals and that your code is not modular.

One solution would be to write your grid.js file in a way that's exposing a Grid component which can be instanciated and which encapsulates it's logic, so that the index.html page can create independent Grid component instances.

You can think of your grid or any UI component as re-usable components such as native <select> element.

What could you do with 2 select elements in the same page?

index.html

$(function () {
    var $select1 = $('#select-1'), //this could be staffGrid = new Grid('#staff-grid')
        $select2 = $('#select-2');

    //Make a parallel with the change event and your gridLoadComplete event.
    //gridLoadComplete should be fired by your grid component itself and your component
    //should allow to listen to those events.

    //It could be staffGrid.on('loadComplete', function () { staffGrid.getValue(); });
    $select1.change(function () {
        $select1.val(); //access select1 value
    });

    $select2.change(function () {
        $select2.val(); //access select2 value
    });
});

As you can see in the exemple above, we invoke the same val function to get the value, but against different instances which allows us to get the value we want without duplicating the val function's logic.

Upvotes: 2

Hadi
Hadi

Reputation: 181

You should consider namespacing your javascript, such that each fragment has its own namespace. For example:

staffGrid.html would contain:

<script>
var staffGrid = {
    gridLoadComplete: function() {
        var data = getValue();
    },

    myOtherFunc: function() {
        //Do other stuff...
    }
};
</script>

Then in your index.html, you can call: staffGrid.gridLoadComplete(); and teacherGrid.gridLoadComplete();

Upvotes: 0

Related Questions