Martyn Ball
Martyn Ball

Reputation: 4885

jQuery Plugin Initialise function not executing

for some reason the initialise function isn't being called when I call my jQuery plugin, this seems to work as expected on another plugin I have created.

Plugin:

(function($) {
    $.fn.youtubeVids = function( options ) {
        var settings = $.extend({
      num: 1,
      id: 'UCeNOYP-TQK-3P3JZerCjheQ',
      elm: null
    }, options );

        function initialize() {
            console.log('dsad');
      $.ajax({
            url: "channel-videos.php",
            data: { num: settings.num, id: settings.id },
            success: function(data) {
                if (settings.elm !== null) {
                    console.log("test");
                } else {
                    console.log("uh oh");
                }
            },
            dataType: "json"
        });
        }
    };
}(jQuery));

Call to the plugin:

<script src="/js-src/youtube-min.js"></script>
<script>
$("#vid1").youtubeVids({
  num: 3,
  elm: [ "#vid1", "#vid2", "#vid2" ]
});
</script>

Upvotes: 1

Views: 36

Answers (1)

Dekel
Dekel

Reputation: 62556

The initialize function inside your youtubeVids function is never getting called, so basically nothing happens there (besides creating the settings variable and the initialize function.

You should call the initialize function inside:

(function($) {
  $.fn.youtubeVids = function( options ) {
    var settings = $.extend({
      num: 1,
      id: 'UCeNOYP-TQK-3P3JZerCjheQ',
      elm: null
    }, options );

    function initialize() {
      console.log('dsad');
      $.ajax({
        url: "channel-videos.php",
        data: { num: settings.num, id: settings.id },
        success: function(data) {
          if (settings.elm !== null) {
            console.log("test");
          } else {
            console.log("uh oh");
          }
        },
        dataType: "json"
      });
    }
    initialize();
  };
}(jQuery));

$("#vid1").youtubeVids({
  num: 3,
  elm: [ "#vid1", "#vid2", "#vid2" ]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vid1"></div>

Upvotes: 2

Related Questions