JQuery click event does not work when using "Pattern Pattern"

I am the JS developer middleware and I am trying the module template described by Chris Koyer here .

But when I store the jQuery selector in the settings, I cannot use it to fire the click event. See the code below with my comments ... Any help is greatly appreciated!

var s, TestWidget = { settings: { testButton: $("#testing") }, init: function() { s = this.settings; this.bindUIActions(); }, bindUIActions: function() { console.log(s.testButton); // This works: [context: document, selector: "#testing", constructor: function, init: function, selector: ""…] //This doesn't work - why????? s.testButton.click(function() { //Why isn't this triggered? alert('testButton clicked'); }); /*This works, obviously: $('#testing').click(function() { alert('testButton clicked'); }); */ } }; $(document).ready(function() { TestWidget.init(); }); 
+6
source share
1 answer

The problem is that you initialize $("#testing") before the DOM is ready, so this jQuery object is empty.

A simple solution is to put all your code in a ready-made callback.

Another option is to replace

  settings: { testButton: $("#testing") }, init: function() { s = this.settings; this.bindUIActions(); }, 

with

  settings: { }, init: function() { s = this.settings; s.testButton = $("#testing"); this.bindUIActions(); }, 

But it’s hard to understand why you are using such code for such a simple thing. Perhaps you are abusing the template and not very clean, since you have two global variables s and TestWidget , when there will already be a lot of them.

Here is a small variation of your code, which, in my opinion, would be cleaner, although it still used modules ( IIFE option ):

 TestWidget = (function(){ var settings = {}; return { init: function() { settings.testButton = $("#testing"); this.bindUIActions(); }, bindUIActions: function() { console.log(settings.testButton); settings.testButton.click(function() { alert('testButton clicked'); }); } } })(); $(document).ready(function() { TestWidget.init(); }); 

settings is stored in closure and does not leak in the global namespace. Please note that even this version does not make sense if you are not doing more with the module.

+10
source

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


All Articles