2014-01-06 29 views
1

我目前正在使用JQuery Boilerplate編寫插件。不過,我有問題調用函數不在init()函數內調用。樣板註釋聲明可以通過init函數內的this.functionname()調用函數,但如果從別處調用它,我不確定如何執行此操作。如何在JQuery Boilerplate中使用JQuery Proxy

從這裏查看其他問題,看起來像我可以使用JQuery代理,但是沒有看到如何將其應用於樣板文件的示例。 有人能告訴我,比如我怎麼會內onEnterMobile調用this.createCarousel()或this.settings從請:

;(function ($, window, document, undefined) { 

    // Create the defaults once 
    var pluginName = "dcResponsiveCarousel", 
     defaults = { 
      itemsPerPageOnMobile: 1, 
      itemsPerPageOnTablet: 2, 
      itemsPerPageOnDesktop: 3 
     }; 

    // The actual plugin constructor 
    function Plugin(element, options) { 
     this.element = element; 
     $element = $(element); 
     this.settings = $.extend({}, defaults, options) ; 
     this._defaults = defaults; 
     this._name = pluginName; 
     this.init(); 

    } 

    Plugin.prototype = { 

      init: function() { 
       enquire 
       .register("screen and (max-width:767px)", this.onEnterMobile) 
       .register("screen and (min-width:768px) and (max-width:991px)", this.onEnterTablet) 
       .register("screen and (min-width:992px)", this.onEnterDesktop)   
      }, 

      onEnterMobile: function(){ 
       var deviceType = "mobile"; 
       console.log(deviceType); 
       //this.createCarousel($element, itemsPerPage, deviceType); 

      } 
     } 
    }; 

    // A really lightweight plugin wrapper around the constructor, 
    // preventing against multiple instantiations 
    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, 
       new Plugin(this, options)); 
      } 
     }); 
    }; 

    })(jQuery, window, document); 
+0

當您說「從其他地方調用」時,是否可以概述代碼中「其他地方」的實際位置? – iamwhitebox

+0

回答我最後一句中的任何一個問題都是其他地方的例子 –

回答

1

OK尋求在這個問題上,我想我會發布一些脫機幫助後jQuery的代理的例子可以JQuery的樣板中使用:

init: function() { 
     var that = this; 
     enquire 
     .register("screen and (max-width:767px)", $.proxy(this.onEnterMobile,this)) 
     .register("screen and (min-width:768px) and (max-width:991px)", $.proxy(this.onEnterTablet,this)) 
     .register("screen and (min-width:992px)", $.proxy(this.onEnterDesktop,this)) 
    }, 

因此而不僅僅是打電話this.onEnterMobile我打電話從內另一種「代理」功能,功能,然後允許我通過我的回調函數通過「this」關鍵字的值。這允許我使用this.settings從插件中的任何函數訪問我的設置,或使用this.functionName調用任何其他函數。函數名稱