2014-02-19 42 views
0

我使用阿迪·奧斯馬尼的優秀jQuery插件模式來編寫一個jQuery插件(http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns),但有一些混淆我約他補充道功能的原型方式:關於阿迪·奧斯馬尼的jQuery插件模式:調用函數

// The actual plugin constructor 
function Plugin(element, options) { 
    this.element = element; 

    // jQuery has an extend method that merges the 
    // contents of two or more objects, storing the 
    // result in the first object. The first object 
    // is generally empty because we don't want to alter 
    // the default options for future instances of the plugin 
    this.options = $.extend({}, defaults, options) ; 

    this._defaults = defaults; 
    this._name = pluginName; 

    this.init(); 
} 

Plugin.prototype.init = function() { 
    // Place initialization logic here 
    // We already have access to the DOM element and 
    // the options via the instance, e.g. this.element 
    // and this.options 
}; 

在本節中,他稱之爲「this.init()」,這是一個添加到插件原型的函數,但是如果我將自己的函數添加到原型中,我無法從任何'this'改變範圍。

E.g.

$('.some-class).each(function() { 
    this.foo(); 
}); 

因爲 '這' 指的是在選擇的每個元素:

Plugin.prototype.foo = function() {}; 

不能從被調用。

如何以標準方式從插件中調用方法和函數? 這些方法不工作,要麼:

Plugin.foo(); 
this.foo(); 

編輯:實際代碼:

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

    var pluginName = 'slider', 
     defaults = { 
      speed: 1000, 
      pause: 5000 
     }; 


    function Plugin(element, options) { 

     this.element = element; 
     this.options = $.extend({}, defaults, options) ; 

     this._defaults = defaults; 
     this._name = pluginName; 

     this.init(); 
    } 


    Plugin.prototype.init = function() { 

     var $slider, 
      $controls; 

     $slider = $(this.element); 
     $controls = $slider.find('.slider__controls'); 

     $controls.each(function(index) { 

      // How do I call 'showControl();'? 

     }); 

    }; 


    Plugin.prototype.showControl = function() { 

     // Do things. 

    }; 


    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
      } 
     }); 
    } 

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

不能從jQuery''調用每個init'() 「要麼。你也可以從構造函數中調用你的方法。 – Bergi

+0

你在哪裏創建了'new Plugin'實例?請告訴我們您的完整代碼。 – Bergi

+0

好吧,我添加了實際的代碼。感謝您幫助他們! –

回答

1

How to access the correct `this` context inside a callback?

Plugin.prototype.init = function() { 
    var $slider = $(this.element), 
     $controls = $slider.find('.slider__controls'), 
     pluginInstance = this; 

    $controls.each(function(index) { 
     pluginInstance.showControl(this); 
    }); 
}; 
+0

優秀,這就是訣竅。 我知道這是'this'的問題,但是對這種模式並不熟悉,我沒有完全明白爲什麼;-) –