2012-04-18 42 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)); 
     } 
    }); 
};