1

I'm working on a small project using Laravel and Vuejs everything is okey with me i loved this two frameworks. i have just a small error when i try to access to goToStep function using jQuery $.each.

By the way jQuery is already included and works fine. the only problem is i can't access to goToStep inside $.each.

Error Message :

Uncaught (in promise) TypeError: this.goToStep is not a function

My VuejS code :

store: function () {
            axios.post("/apartment/", $("form#add-apartment").serialize()).then((response) => {
                this.buildings = response.data.buildings;
                alert(response.message)
            }).catch(error => {
                //console.log(error.response.data.errors)
                $.each(error.response.data.errors, function(key, value){
                    var x = $("[name='"+ key +"']").closest("#parent").data('step');
                    this.goToStep(x)
                });
            });
        },
        goToStep: function (value) {
            if (!this.validate()) {
                return;
            }
            this.current_step = value;
        },
Alice Munin
  • 511
  • 2
  • 13
  • 1
    Change `function(key, value) {` into `(key, value) => {` to encapsulate the `this` context around the `$.each`. More info [here](https://stackoverflow.com/a/34361380/1913729) – blex Aug 15 '20 at 23:32
  • Thank you man so much, fixed – Alice Munin Aug 15 '20 at 23:45

1 Answers1

0

Replace

$.each(error.response.data.errors, function(key, value){
   var x = $("[name='"+ key +"']").closest("#parent").data('step');
   this.goToStep(x)
});

...with:

$.each(error.response.data.errors, key => this.goToStep(
  $(`[name='${key}']`).closest('#parent').data('step')
));

What I did:

  • replaced your anonymous function with an arrow function, so the outer this becomes available inside of it
  • removed value (second) param, since you're not using it anywhere inside the function
  • removed var declaration (no point in declaring it if you only reference it once - you can simply replace the reference with the actual code being assigned to var, while avoiding context pollution).
  • replaced string concatenation with template literals - reduces size and increases readability, IMHO
tao
  • 69,335
  • 13
  • 103
  • 126