jeudi 28 mai 2015

Design pattern help: jQuery working with mutiple elements

I'm new to jQuery. I wanted to know what's the best way to access the element when I am using the same element across multiple functions in the same .js file Below are the two approaches I can think of. I have scoped functions ( F1 & F2) as well as other functions(F3,F4). I want to use elements in some or all of these functions. Whats the best way.

Approach 1

    var elm1 = $("#ID1")
    var elm2 = $("#ID2")
    var elm2 = $("#ID3")

    $(function () {

        function F1() {
            // work with elm1,elm2,elm3
        }

        function F2() {
            // work with elm1,elm2,elm3
        }    
    })

    function F3() {
        // work with elm1,elm2,elm3
    }

    function F4() {
        // work with elm1,elm2,elm3
    }

Approach 2

    var id1 = "#ID1";
    var id2 = "#ID2";
    var id3 = "#ID3";

    $(function () {

        function F1() {
            // get elements usings IDs
            var elm1 = $(id1)
            var elm2 = $(id2)
            var elm3 = $(id1)
        }

        function F2() {
            // get elements usings IDs
            var elm1 = $(id1)
            var elm2 = $(id2)
            var elm3 = $(id1)
        }   
    })

    function F3() {
        // get elements usings IDs
        var elm1 = $(id1)
        var elm2 = $(id2)
        var elm3 = $(id1)
    }

    function F4() {
        // get elements usings IDs
        var elm1 = $(id1)
        var elm2 = $(id2)
        var elm3 = $(id1)
    }

on other note, what terminology we use for functions F3 & F4? Global Functions?

Aucun commentaire:

Enregistrer un commentaire