0

I have multiple products on my page and want to create an associative array holding the product number as key and the JQuery element as value so I created this interface

interface ProductMap<T extends JQuery> {
    [productNumber: string]: T;
}

Then, in my class, I initialize it protected elements: ProductMap<JQuery> = {}; and want to fill it with data later on

const products = $(selector);
if (products.length > 0) {
    $.each(products, function (index, product) {
        this.elements[$(product).data('product-number')] = $(product);
    });
}

However, I'm always getting the error

Uncaught TypeError: Cannot set property '{product-number}' of undefined

How exactly do I create such an associative array?

2
  • Why don't you use a map? Commented Sep 25, 2017 at 7:31
  • I read that it only works when compiling in ES6 and we compile in ES5 Commented Sep 25, 2017 at 7:32

1 Answer 1

1

this.elements is undefined since you change your context using $.each. Keep a reference to your instance in order to fix this problem :

const products = $(selector);
var self = this;

if (products.length > 0) {
    $.each(products, function (index, product) {
        self.elements[$(product).data('product-number')] = $(product);
    });
}

You could also use bind to achieve this.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks! Everything being a separate context is hard getting used to when coming from other languages. Totally forgot about that again. Thank you
@Musterknabe If you can use the fat arrow notation $.each(products, (index, product) => {...}); you might don't need to save the context btw.
@kevinSpaceyIsKeyserSöze This is still ES6.
@NathanP. You can write ES6 and compile it as ES5
@kevinSpaceyIsKeyserSöze I know, but it seems that it's not something OP wants, as he said in his previous comment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.