MarkusH / django-osm-field

http://markush.github.io/django-osm-field
MIT License
29 stars 12 forks source link

TypeError: $(...).osmfield is not a function #6

Closed Fisiu closed 8 years ago

Fisiu commented 8 years ago

Hi, when I try to use this in admin panel, with plain django 1.8 - it works fine. But when we add some admin packages, like django-easy-select2 which uses jquery as well, then this package fails to start, and firebug shows:

TypeError: $(...).osmfield is not a function

I fixed issue by replacing line in osm_field.(min)?.js from

(function($) {

into

jQuery(document).ready(function(jQuery) {

and removing

(jQuery)

from the last line.

Not sure it's a good approach, but it works at least ;-)

MarkusH commented 8 years ago

jQuery has a noConflict() thing https://api.jquery.com/jquery.noconflict/ you might want to try. Happy to review a PR :smile:

netAction commented 8 years ago

This is a wrapper that makes the script independent from noconflict mode:

jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});

https://api.jquery.com/jquery.noconflict/

Wondering how your solution could work as you never defined $.

MarkusH commented 8 years ago

I have no idea. I have no idea how the JS magic works, to be honest. I you say, "A" is the best solution out there, sure, I'll go with that. :wink:

blag commented 8 years ago

@Fisiu: I highly suspect that django-easy-select2 is loading jQuery a second time, which resets the jQuery plugins that are loaded. That would cause the error you are seeing.

According to the documentation, plugins for jQuery are not supposed to be initialized in jQuery(document).ready(), because other functions defined in ready() may want to use your plugin, which may not be defined yet, and it's difficult to adjust the order of functions in ready().

I don't think jquery.noconflict is applicable here because jQuery is being loaded in both cases.

So yeah, keep the code like this - just the way it is now, it's the proper way to do it:

(function ($) {
    $.fn.osmfield = function () {
        ...
    }; // jQuery plugin end
}(jQuery));
blag commented 8 years ago

I'm closing this because I don't think noconflict is the answer, the code is following jQuery's best practices, I don't think there's really anything this project can do to fix the suspected issue, and I cannot reproduce the issue myself (except for loading jQuery twice - which this project can't fix).

Please feel free to reopen if it pops up and you're 100% sure you are loading jQuery twice. Cheers!