I’ve been experimenting with Element storage, and I’m stumped by a problem with .retrieve(); in Element Storage.
The documentation states:
Element:retrieve actually accepts an optional second parameter which will act as the default value to store if another value doesn’t previously exist. It will then retrieve the value as expected.
Basic examples work, but when I am instantiating a Class in the second parameter, that instantiation gets run every time, even though I can verify that .retrieve(); is returning the Class object that was instantiated prior.
If you take a look at the fiddle, you can see that every time you click the div, myClass gets instantiated again. Ideally, it should be instantiated once, that object should be saved into Element storage, and retrieves properly in order to stop it from being instantiated again.
This is how I am calling .retrieve();:
$('baz').addEvent('click', function() {
this.retrieve('foobar', new myClass()).foo();
});
… and just for fun, I tried this (it also didn’t work):
$('baz').addEvent('click', function() {
this.retrieve('foobar', (function() {
return new myClass();
})()).foo();
});
… and here is how I finally got it to work, by NOT using .retrieve()‘s second parameter:
$('baz').addEvent('click', function() {
var instClass = this.retrieve('foobar');
if (instClass == null) {
instClass = this.store('foobar', new myClass()).retrieve('foobar');
}
instClass.foo();
});
Any clue what’s causing this behaviour?
The second argument always gets evaluated, yes. In your case, a new instance of
myClassis instantiated with everyretrievecall – that’s what you see in the console. This will always happen, regardless of the outcome of the call or whether the parameter is actually processed in the method (you could pass e.g. 10 more parameters to the method, they will all get evaluated at the moment of the call).In your case, there is another misunderstanding: when the default parameter of theretrievecall is used, it won’t be stored automatically. Therefore your third variant is actually the right solution to the task(Updated – I was wrong with my second state statement, as @Julian H. Lam pointed out: the second parameter to
retrieveis actually immediately stored.)