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
user991349user991349
-
1Why have you tagged this as jQuery? Do you want a jQuery solution?deed02392– deed023922012年03月16日 09:14:29 +00:00Commented Mar 16, 2012 at 9:14
-
because i am using jquery to bind the load event. a solution in jquery would also suffice.user991349– user9913492012年03月16日 09:19:58 +00:00Commented Mar 16, 2012 at 9:19
1 Answer 1
3 Comments
Sushil
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 Sushil
@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.
lang-js