Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Uncaught Type error cannot assign to read only property

Hi,
I am getting the following error in console :
User generated image
This is the code that causes it :
 var event = new Event('select');
        event.chat = chat;
        if (name) {
            event.chatName = name;
        }
        self.dispatchEvent(event);

Open in new window


previously i was using the following code but then i found that the initEvent thing is deprecrated :
var event = document.createEvent('Event');
        event.initEvent('select', true, true);
        event.chat = chat;
        if (name) {
            event.chatName = name;
        }
        self.dispatchEvent(event);

Open in new window


dispatchEvent = function (event) {
    if (!(event.type in this.listeners)) {
        return;
    }
    var stack = this.listeners[event.type];
    event.target = this;
    for (var i = 0, l = stack.length; i < l; i++) {
        stack[i].call(this, event);
    }

Open in new window


This is the code that gets called when an event is dispatched...
And the line : event.target = this;  is the place where error is thrown....

Why this read only error is getting thrown... However if i put a break point at any line or otherwise also write in console : event.target = this; or anything else... it doesnt throw any error .

Why is this read only error getting thrown.. All basically i am doing here is exposing a custom Event object... and have the ability to dispatch it...

Probably also i can do it in different way then constructing an Event object..

Thanks
ASKER CERTIFIED SOLUTION
Avatar of James Bilous
James Bilous
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj

ASKER

But i can create the Event object in browser console and assign the target porperty to it...
It doesnt error out there...
It doesn't error but it doesn't work - its simply failing silently. After you assign the event target try printing it out. You'll see it is still undefined.
so is it that event target is automatically set ?
what do you suggest should event target be set or not ?
as in normal listeners like mouseover etc...the event does have a target property set... so i was thinking in my custom event also the target property should have been set...
is it documented somewhere that target property is read only ?
Yes, check here for the Event API: https://developer.mozilla.org/en-US/docs/Web/API/Event

I would not recommend setting properties of event objects, it is primarily for the browser to work with user interactions and to communicate with the shadow DOM. Messing with the event target would be dangerous and could violate encapsulation so it makes sense that they do not let the developer change it.