-2

I have the following script which is calling a map() function:

$(function () {
  $.getScript("https://www.google.com/jsapi", function() {
    google.load("maps", "3", { callback: function() {

      console.log("loaded");
      $.mapit();

    }});
  });  
});

Where map is the following function:

$(function () {      
  $.fn.mapit = function () {        
    console.log("map called");      
    return $(this);    
  } // mapit    
});

On my console I see "loaded" but not "map called" and I do not get any error.

What am I missing?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • what a weird way to declare the functions. Is there any reason you did it that way, instead of making something like `function map(){ ... }` as usual? I'm actually curious – Shinra tensei Sep 08 '17 at 11:54
  • https://stackoverflow.com/a/3090236/2968762 – Abhi Sep 08 '17 at 11:55
  • oh I see, thank you – Shinra tensei Sep 08 '17 at 11:56
  • 1
    $.map is already a function in JQuery, and you're not overriding it but extending the prototype (I believe that makes a difference, I could be wrong though). – Adrian Sep 08 '17 at 12:02
  • `$.fn.somethingHere` is the syntax for starting a jquery plugin. It's not at all clear what you're trying to do. – Jamiec Sep 08 '17 at 12:10
  • @Adriani6 You are right. map is already a function. So I changed the name to mapit and now when I call it I get the error "$.mapit is not a function". I updated my code. What am I missing? – Miguel Moura Sep 08 '17 at 14:22
  • 1
    @MiguelMoura It's still not a function because you extended the JQuery object, you need to do something like $("div").mapit() if I'm not mistaken, I haven't extended JQuery in ages but if I recall correctly that's it but don't take my word for it. – Adrian Sep 08 '17 at 14:24
  • @Jamiec Map is a function that will use JQuery to do a few things but only after Google Loader loads Google Maps. And the function Map (MapIt now) should only be available aftre JQuery is loaded. that is why I used $function. Does this make sense? – Miguel Moura Sep 08 '17 at 14:24
  • @MiguelMoura You could use $(document).ready and a promise from your Google Loader as an alternative. – Adrian Sep 08 '17 at 14:25
  • @Adriani6 you are correct about using $("div") – Miguel Moura Sep 08 '17 at 14:27
  • @MiguelMoura See the Answer for a follow up. – Adrian Sep 08 '17 at 14:32

1 Answers1

1

Concluding the conversation in the comments, To extend the JQuery utility the way you specified in the Question, you would have to do

jQuery.extend({
    mapit : function(){
        console.log("map called");
    }
});

To call it you can now do $.mapit();

How ever extending the JQuery objects you would do

$.fn.mapit = function () {        
    console.log("map called");        
} 

To call the above however you need a JQuery object such as $("div").mapit();

Adrian
  • 8,271
  • 2
  • 26
  • 43