Friday 15 August 2014

jQuery plugin how to add events? -


OK, so I'm new to the jQuery plugin game and I've read a lot and it just seems that the jQuery plugin There are 27 million ways to write For example, take this base plugin pattern:

 ; (Function ($, window) , document, undefined) {var pluginName = 'MyPlugin'; Var defaults = {propertyName: "value"} function plugin (element, option) {this.options = $ .extend ({}, default, options); _defaults = defaults; This._name = pluginName; This.element = element; This.init ();} Plugin.prototype = {init: function}} {/ some ion function}, some method: function (L, option) {// DO SOTHTHING}} $ .fn [pluginName] = function Option) {return.Each (function (! ($! $. Data (this, 'plugin_' + plugin name)) {$. Data (this ('plugin', plugin), 'plugin_' plugin name, new plugin (This, option); and if ($ .isfunction (plugin.protopp [options]) {$ .data (this, 'plugin_' + pluginname) [option] ();}}}}}}}) , Window, document);   

Then we have this simple HTML:

  & lt; a href = " In my plug, we say that we wanted to alert href when the link is clicked and the default action is taken in the link "gtc: mediawidth"   

Obviously this is actually a bad example and the path I want to do is more intense, so please do not say that 'you do not need a plugin for this' because it is not here.

Then we include our plug-ins on our link:

  $ (ten Document) .ready (function () {$ ( 'a'). Each (function () {$ (this) .MyPlugin ();});});   

I do not know if there is a way to add a click: method and simply it is called itself or can some kind of internal event be binding?

I will only add one click event to the init function, then this is cleaner

  Plugin.prototype = {init: function () {// DO INIT $ (this.element) .on ("click", function (e) {e.preventDefault (); warning ($ (this) .attr ("Href"));}); }, Some method: function (L, option) {// DO SOTHTHING ELSE}};   

Or,

You can put it only on a different method:

 ; (Function ($, window, document, undefined) {var pluginName = 'MyPlugin'; var defaults = {propertyName: "value"} function plugin (element, option) {this.options = $ .extend ({}, default, Option); this._defaults = defaults; this._name = pluginName; this.elename = element; this.init (); this.attachEvents (this.element, this.options);} Plugin.prototype = {init: function ( ) {// DO INIT}}, AttachEvents: function (L, Options) {$ (L) .on ("click", function (e) {e.preventDefault (); Alert ($ (this) .attr (" Href "))}};}} $ .fn [pluginName] = function (option) {return.Each (function () (if (! $. Data (this, 'plugin_' + plugin name)) {$. Data ( This, 'plugin_' + pluginname, new address (This, option); and if ($ .isfunction (plugin.protopp [option]) {$ .data (this, 'plugin_' + pluginname) [option] (option;);}});}}) (jquery , Window, document); $ (document) .ready (function () {$ ('a'). MyPlugin ();});    

No comments:

Post a Comment