I am trying to make a Proxy
object of Image
to trap properties but even with an empty handler I get an error message.
TypeError: Argument 1 of Node.appendChild does not implement interface Node.
The proxy object is suppose to act as the target object so this baffles me a little. As far as I understand you should be able to do this with DOM nodes as well (?).
Also: I cannot start loading the image and have the onload
handler triggered when setting the src
property.
How should I use the Proxy so I can "take over" for example the "src" property and otherwise have it act like a regular image object?
My code
'use strict';
//--- normal image use ---
var imgNormal = new Image();
imgNormal.onload = function(){
console.log('Normal loaded OK');
document.body.appendChild(imgNormal);
};
imgNormal.src = 'https://i.imgur.com/zn7O7QWb.jpg';
//--- proxy image ---
var imgProxy = new Proxy(Image, { // I also tried with 'new Image()' and HTMLImageElement
set: function(a,b,c,d){
console.log('set '+b);
return Reflect.set(a,b,c,d);
}
});
imgProxy.onload = function(){
console.log('Proxy loaded OK');
document.body.appendChild(imgProxy);
};
imgProxy.src = 'https://i.imgur.com/zn7O7QWb.jpg';
document.body.appendChild(imgProxy); // double-up to demo error
Update: Thanks to @Harangue! using " now I am unable to trap the setting of properties. It seem to ignore the trap completely - example:new
" (bah..) certainly made the proxy object come to life but
var proxy = new Proxy(Image, {
set: function(a,b,c,d){
console.log('set '+b); // doesn't show
return Reflect.set(a,b,c,d);
}
});
var imgProxy = new proxy();
imgProxy.onload = function(){
console.log('Proxy loaded OK');
document.body.appendChild(imgProxy);
};
imgProxy.src = 'https://i.imgur.com/zn7O7QWb.jpg';
How can I trap the property setting using a valid proxy?
Update 2 On the other hand - using new
with the new proxy only seem to use the original constructor. All examples I can find does not use new:
var myProxy = new Proxy(.., ..); // should suffer
Using then on top of that new myProxy()
only seem to use the original constructor which is not what I want as it ignores the traps.
var proxy = new Proxy(Image, {}); //should be sufficent??
var proxy2 = new proxy();
console.log(proxy2); //-> says Image (not proxy..)
The traps seem to work in my first attempts but the proxy doesn't behave as expected. This is so confusing, and so new. Happy for any input how both of these can be solved (traps and behavior).