javascript - jQuery click event not working while using "Module Pattern" -


i'm intermediate front-end js developer , i'm trying module pattern outlined chris coyyer here.

but when store jquery selector in settings, i'm unable use trigger click event. see below code comments... appreciated!

var s, testwidget = {   settings: {     testbutton: $("#testing")   },   init: function() {     s = this.settings;     this.binduiactions();   },   binduiactions: function() {     console.log(s.testbutton); // works: [context: document, selector: "#testing", constructor: function, init: function, selector: ""…]      //this doesn't work - why?????     s.testbutton.click(function() {         //why isn't triggered?         alert('testbutton clicked');     });      /*this works, obviously:     $('#testing').click(function() {         alert('testbutton clicked');     });     */    } }; $(document).ready(function() {     testwidget.init(); }); 

the problem initialize $("#testing") before dom ready, jquery object empty.

a simple solution put code in ready callback.

another 1 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 why use code such simple thing. might overusing pattern here , it's not clean have 2 global variables s , testwidget when 1 lot.

here's slight variation of code be, in opinion, cleaner, while still using modules (iife variant) :

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 kept in closure , doesn't leak in global namespace. note version doesn't make sense if don't more module.


Comments