brad
brad

Reputation: 32335

Adding events on load

I'm having a problem getting a change event to register with the following code:

var map = function(){

  function addMapTriggers(){
    $("#map_form select").change(getDataWithinBounds);
  }

 return{
  init: function(){
   getDataWithinBounds();
   addMapTriggers();
  }
 };
}();

and in a jQuery document.ready:

$(function(){
  map.init();
});

So I get my initial data, then every time I change one of the selects, I get the map data again (getDataWithinBounds sends an ajax call). Problem is, it doesn't work, the change event is never added.

However, if, in the console I type map.init(); it does work. This is weird, I don't understand how there is any difference whatsoever? What am I missing here? I'm testing this on Safari AND Firefox with the exact same behavior.

Upvotes: 2

Views: 859

Answers (3)

brad
brad

Reputation: 32335

I'm so embarrassed right now and I apologize for wasting everyone's time. Of course the above code works, what's different about what I'm doing is that my site is using the jquery selectbox plugin, which styles the selects by creating a UL with click events to act like a select (not my choice, trust me) Unfortunately, I was calling init before applying the selectbox code, which itself alters the binding of the selects. Putting the selectbox call first, then calling map.init() completely fixed it.

Many apologies and thanks a lot (SolutionYogi in particular) for taking the time to help me out.

Upvotes: 0

SolutionYogi
SolutionYogi

Reputation: 32233

Is 'map_form' id of your select? If yes, then you should do

$("#map_form").change(getDataWithinBounds);

'#map_form select' will try to hook up change event to all the select which are present in element specified by #map_form.

EDIT:

Noticed one more thing, map.init doesn't really exist.

In your code, map is a named function which is executed immediately which returns an object which has init method. This doesn't mean that 'map' var has the init method.

You want to try something like this,

var map = function()
{

    function addMapTriggers()
    {
        $("#map_form select").change(getDataWithinBounds);
    }

    return {
        init:  function()
               {
                    getDataWithinBounds();
                addMapTriggers();
            }
    };
}();

In above code, you run an anonymous function which returns an object which has init method and assign the result to map. Now map object will have init method and you can do this:

$(function()
{
  map.init();
});

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82483

Why not like this?

function map(){
 return {
  me = this,
  addMapTriggers: function(){
    $("#map_form select").change(getDataWithinBounds);
  },
  init: function(){
   getDataWithinBounds();
   me.addMapTriggers();
  }
 };
}();

Upvotes: 0

Related Questions