K
K
Klaus Kater2015-03-17 13:13:37
JavaScript
Klaus Kater, 2015-03-17 13:13:37

Strange delegation in js? Why are objects not copied?

Hello. There is such a construction, an object, with a bunch of processing for all sorts of drops, clicks, etc.
I'm trying to create a second object, almost the same as the first one, but one of the handlers needs to be replaced.
With such a construction (code below), the handler is simply hung up next, both on the original object and on the new one.
Do not swear loudly, I still don’t understand the js OOP system, but I’m trying.
The console clearly shows the sequential call of 2 functions.

var item = $('#container1');    // Делаю объект из дом элемента
item.target = $(item).children('.target');    // Дропы принимает не сам объект, а один из дочерних узлов (так надо)
// тут куча обработок
// и наконец сам обработчик дропа
item.target.on('drop', function(e) {
    console.log('Drop');
});

var item_2 = {};
item_2.__proto__ = item;    // пытаюсь скопировать объект
// пытаюсь переназначить обработчик
item_2.target.on('drop', function(e) {
    console.log('Drop 2');
});

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kazmiruk, 2015-03-17
@kazmiruk

You have item.target and item_2.target - the same object, on which you hang the event. When item_2.target is called, target is first searched for in item_2, then it does not find it and climbs into item as a prototype.

N
Nikita, 2015-03-17
@Rema1ns

usually copy objects via clone()

K
Klaus Kater, 2015-03-17
@kurojneko

item_if = $(item).clone(true);
item_if.target - undefined
What am I doing wrong?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question