2012-04-18 43 views
1

我遵循這個常見的設計模式爲樣板jquery插件,並且我無法從原型中的任何位置調用構造函數中的特權方法this.service()。我怎樣才能從原型中調用this.service(),而不僅僅是在原型的初始化中?如何使用jquery插件調用特權方法。 Boilerplate jquery設計模式

總的來說,我想要做的就是能夠訪問這個插件中的一個變量,它只會在插件的這個實例中受到影響和改變。這個變量應該放在別的地方嗎?我的代碼中該變量名爲variableToAccess。也許我來到這一切都是錯誤的。謝謝。插件在

被稱爲如下

$('article').comment(); 

這裏是插件

;(function ($, window, document, undefined) { 
    // Create the defaults once 
    var pluginName = 'defaultPluginName', 
     defaults = { 
     propertyName: "value" 
    }; 

    // The actual plugin constructor 
    function Plugin(element, options) { 
     this.element = element; 
     this.options = $.extend({}, defaults, options) ; 
     this._defaults = defaults; 
     this._name = pluginName; 
     var variableToAccess = false;//<----should this be somewhere else? 
     this.service = function() { 
      variableToAccess = true; 
     }; 
     this.init(); 
    } 

    Plugin.prototype = { 
     init: function() { 
      Plugin.prototype.doSomething(); 
     }, 
     doSomething: function() { 
      this.service()//<----doesn't work 
     } 
    } 

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

})(jQuery, window, document); 

回答

0

我可能是不正確的在這裏,但我不相信你應該調用DoSomething的(),通過插件。 prototype.doSomething()。

this.doSomething();應該調用該方法。請看下面:

function Plugin(element, options) { 
    this.element = element; 
    this.options = $.extend({}, defaults, options) ; 
    this._defaults = defaults; 
    this._name = pluginName; 
    var variableToAccess = false; 
    this.service = function() { 
     variableToAccess = true; 
    }; 
    this.init(); 
} 

Plugin.prototype = { 
    init: function() { 
     this.doSomething(); 
    }, 
    doSomething: function() { 
     this.service(); 
    } 
}; 

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