Scoping JavaScript Problem za pomocą JQuery Boilerplate
Używam JQuery Boilerplate do napisania mojej pierwszej wtyczki JQuery - responsywnej karuzeli. Używam innej wtyczki (SSM -http://www.simplestatemanager.com/) do tworzenia stanów dla każdego widoku urządzenia. Tak więc na urządzeniach mobilnych będzie działać funkcja A, na tabletach functionB i na desktopach functionC itd.
Dla każdego stanu utworzonego przez SSM można dodać odpowiednią funkcję zwrotną onEnter i dodałem 3 odpowiednie funkcje do uruchomienia, gdy to nastąpi. Jak widać z poniższego kodu, funkcja onEnterDesktop działa na urządzeniach stacjonarnych. Próbuję następnie uruchomić dalszą funkcję z tego wnętrza o nazwie createCarousel (), ale pojawia się błąd „createCarousel nie jest zdefiniowany”.
Uważam, że jest to spowodowane problemem z zakresu i przeglądarka nie może znaleźć funkcji createCarousel z poziomu funkcji onEnterDesktop. Jak mogę to naprawić?
Każda pomoc byłaby świetna. Oto kod mojej wtyczki:
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = "dcResponsiveCarousel",
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.$element = $(element);
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
ssm.addStates([
{
id: 'mobile',
maxWidth: 767,
onEnter: this.onEnterMobile
},
{
id: 'tablet',
maxWidth: 991,
minWidth: 768,
onEnter: this.onEnterTablet
},
{
id: 'desktop',
minWidth: 992,
onEnter: this.onEnterDesktop
}
]);
ssm.ready();
},
onEnterMobile: function (){
console.log("You've entered mobile screen dimension territory");
var itemsPerPage = 1;
console.log(itemsPerPage);
},
onEnterTablet: function (){
console.log("You've entered tablet screen dimension territory");
var itemsPerPage = 2;
console.log(itemsPerPage);
},
onEnterDesktop: function (){
console.log("You've entered desktop screen dimension territory");
var itemsPerPage = 3;
createCarousel();
},
createCarousel: function (){
var $carouselItems = this.$element.children(".item"),
$carouselItemsLength = $carouselItems.length,
$carouselItemsWidth = 0;
for (var i = 0; i < $carouselItemsLength; i++) {
$carouselItemsWidth = $carouselItemsWidth + $carouselItems.eq(i).outerWidth();
};
console.log($carouselItemsWidth);
this.$element
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin( this, options ));
}
});
};
})( jQuery, window, document );