mhawksey / wp-evidence-hub

OER Research Hub - WordPress plugin
6 stars 1 forks source link

Reduce number of global Javascript variables, by using a 'super' global ... #49

Open nfreear opened 9 years ago

nfreear commented 9 years ago

Hi,

At the moment a number of the JS files expose a lot of global variables, which can potentially conflict and introduce bugs... For example:

In a recent commit, for issue #47, I introduced a super global, named OERRH (it could be OEREH I supposed - doesn't matter...),

The idea is that the PHP code adds configuration to this one global, and it is then accessed by the included Javascript files. I wonder if there is a way to gradually add to this variable, without clobbering previously added data? Example:

<?php
class Evidence_Hub_Base {

    // ...

    // Definition:
    protected function append_js_config( $js_key, $js_value ) {
        // Sanitize data - ensure $js_key is a string ...
        ?>
<script>
var OERRH = OERRH || {};
OERRH.<?php echo $js_key ?> = <?php echo json_encode( $js_value ) ?>;
</script>
<?php
    }
}

    // Use in PHP:
    $this->append_js_config( 'evidence_map', array(
        'config_a' => 'value',
        'config_b' => array( ... ),
    ));
?>

External Javascript - eg. leaflet-map.js:

jQuery(function ($) {

    var map_config = OERRH && OERRH.evidence_map;

    // ...
});

Does this make sense, and is it OK to add this gradually?

Ta,

Nick

nfreear commented 9 years ago

Having thought about it more, the part of this bug that relates to new functionality, for example #47 and #50 are completely justifiable. The part relating to legacy code (that works!) is not high priority, and I (probably) won't have time in this work-package for LACE (finish, end of May).