JQuery plugin template using "live"

I have many articles about writing object-oriented javascript code and developing a jQuery plugin, as far as I know how they work, and I can create my own plugins.

But there is one problem with all the articles (even with the official plugin development guide - http://docs.jquery.com/Plugins/Authoring ) - all of these templates to wear t support live.

Take for example this template - http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html

$.fn.myplugin = function(options) { return this.each(function() { var element = $(this); // Return early if this element already has a plugin instance if (element.data('myplugin')) return; // pass options to plugin constructor var myplugin = new MyPlugin(this, options); // Store plugin object in this element data element.data('myplugin', myplugin); }); }; 

A new instance of "MyPlugin" will be created for each suitable jQuery object.

How to change it (if possible), so it will work on elements added in the future?

thanks

+4
source share
2 answers

I often enjoyed live success in my plugins as a regular option. Here is a trivial example that adds a warning to the elements that were clicked:

 $.fn.clickAlert = function(settings) { settings = $.extend({live: false}, settings); function clickAlertFn() { alert('Clicked!'); } if (settings.live) { return this.live('click', clickAlertFn); } else { return this.click(clickAlertFn); } }; // this will only work on existing `a` elements with class foo $('a.foo').clickAlert(); // this will work on existing and future `a` elements with class bar $('a.bar').clickAlert({live: true}); 

In this example, everything that works fine with $ ('...'). live ('click', ... ') will work with $ (' ... '). clickAlert ({live: true});

One more thing, in most plugins you do something like this:

 $.fn.foo = function() { return $(this).each(function() { // code in here... }); } 

Unfortunately, using live inside each loop will not work.

+2
source

I find this working (jQuery 1.5.2):

 (function($) { $.fn.clickTest = function () { return this.each(function() { $('.clicker').die('click').live('click', function() { console.log('clicked'); }); $(this).click(function() { $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> '); }); }); }; }) (jQuery); 
+1
source

Source: https://habr.com/ru/post/1333198/


All Articles