1

I am looking for a JS solution / design pattern that allows to call the function C.Test.init() multiple times with binding the window load event in the init() function. Unfortunately I cannot get this to work. Can anyone help me with this?

 var C = {};
 C.Test = (function(C)
 {
 var me = {};
 me.init = function(config)
 {
 me._config = config;
 $(window).bind('load.' + config.name, me, me.sayHello);
 }
 me.sayHello = function(e)
 {
 // this doesn't work:
 document.write('HELLO ' + me._config.name + '<br>');
 // this doesn't work either:
 document.write('SALVE ' + e.data._config.name + '<br>');
 }
 return {
 init : me.init
 }
 })(C);
 C.Test.init({
 name: 'John'
 });
 C.Test.init({
 name: 'Kate'
 });

Here's the JS Fiddle link: http://jsfiddle.net/4Ss8L/

asked Mar 16, 2012 at 9:05
2
  • 1
    Why have you tagged this as jQuery? Do you want a jQuery solution? Commented Mar 16, 2012 at 9:14
  • because i am using jquery to bind the load event. a solution in jquery would also suffice. Commented Mar 16, 2012 at 9:19

1 Answer 1

2

seems like a closure issue to me

http://jsfiddle.net/4Ss8L/2/

check this out.

answered Mar 16, 2012 at 9:34

3 Comments

and if u want the data to be added in event.data then u'll have to do something like this $(window).bind('load.' + config.name, function (c) {return function (e) {e.data = c;me.sayHello.call(this, e);}}(config)); reason being u are using a singleton or rather an object to access data and by the time the window's load is fired the _config is changed and the old reference of data is overridden. here's the fiddle link jsfiddle.net/4Ss8L/3
great. thank you @Sushil! one more question though: is the "return" really needed? it also works without it.
@santacruz no, in your scenario its not needed but in some cases it is, so it's kind of in case to case basis. But if you remove the return statement you'll not get the event object. check our the fiddle link i gave u in my previous comment.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.