brandonhowlett
brandonhowlett

Reputation: 25

Defining jquery variable into function that's out of scope

I'm trying to pass a paramater (gmap_settings) to a function (initialize) that is in an included external js file. My php file looks something like this:

<?php
$setting = array(
    'zoom' => 8
);

$json = json_encode($setting);
?>

<script type="text/javascript">
//<![CDATA[

jQuery(document).ready(function($) {
    var gmap_settings = $.parseJSON ('<?php echo $json; ?>');
--> google.maps.event.addDomListener(window, 'load', $(document).initialize(gmap_settings));
});

//]]>
</script>

For simplicity's sake, lets say that the external js file looks like this:

(function($) {
    var initialize = function( data ) { alert(data); };
})( jQuery );

Regardless of what I try I can't figure out how to pass gmap_settings into initialize(). I've tried function initialize() in the external file:

$(document).initialize.gmap_settings
$(document).initialize({gmap_settings})
initialize(gmap_settings) 

I don't understand what I'm missing.

Upvotes: 0

Views: 621

Answers (1)

dm03514
dm03514

Reputation: 55962

why would you think that $(document).initialize would work?

You could implement the module pattern in your external javascript file and return an object and call initialize on that object

var YourModule = (function($) {
    return {
       initialize: function( data ) { alert(data)} 
    };
})( jQuery );

now you have a variable you can use

var newModule = Object.create(YourModule);
newModule.initialize('This will be alerted')

Upvotes: 1

Related Questions