Sunday, 16 April 2017

How to save variable state with closure

I have a function that i need call several times, and this function will append elements in my html:

class MyClass {

  somefunct(elements) {
    const father = $("#father").find("#other-element");
    for (let element of elements) {
      father.append(element);
    }
  }
}

I would like to avoid call initialize the father in every call. How so?

How i'm doing:

  somefunct(elements) {
    const father = $("#father").find("#other-element");
    this.somefunc = (elements) => {
      for (let element of elements) {
        father.append(element);
      }
    }
  }

And this will work, but i don't know if this is a bad practice, or if there is a better approach.

Thank you.



via FXux

No comments:

Post a Comment