Utilizing this feature in Vue when employing lodash throttle

Starting with this tutorial, I implemented the following code snippet:

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    resizedWindow: _.throttle(this.reset, 200),
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

However, an error message popped up stating:

Uncaught TypeError: Cannot read property 'reset' of undefined

Typically, this issue is related to how this is handled and can be fixed by doing something like this:

// Replace previous resizeWindow method with...
resizedWindow(){
  let vm = this;
  _.throttle(vm.reset, 200);
},

Unfortunately, this modification doesn't trigger the reset method. It seems like there might be a simple solution or a misunderstanding regarding this – how can I correctly implement this functionality?

Answer №1

It appears that in this scenario, the use of this is pointing to the window object. To ensure access to this as the Vue instance, you can relocate the method definition for resizedWindow to the created hook, as demonstrated here.

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  created() {
    this.resizedWindow = _.throttle(this.reset, 200)
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

Another approach would be to utilize an IIFE ..

export default {
  data(){
    return {
      width: 0,
      height: 0,
    }
  },
  methods: {
    resizedWindow() { (_.throttle(this.reset, 200))() },
    reset(){
      this.width = window.innerWidth;
      this.height = window.innerHeight;
    }
  },
  mounted(){
    this.reset();
    window.addEventListener('resize', this.resizedWindow);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering information within an array in MongoDB

Here is a sample collection: { "name":"silver", mywants:[ {"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}, {"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}}, {"_id":objid(5454dfd44545), ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...

Problems Encountered with Basic JSON-P Example

I am currently working on a mobile app project that involves fetching JSON data from a MySQL database using PHP. This is a new venture for me, so I started with a basic example to test things out. Everything works fine when the data is on the same domain, ...

Having difficulty altering the color of my 3D model using three.js

I'm currently facing an issue with my 3D gltf model of a building on a Mapbox Map. Despite trying to change the color using MeshPhongMaterial or other variations, it seems that the color remains unaltered. Everything else appears to be functioning co ...

What is the best way to extract the numerical value from a JavaScript object?

I'm currently working on a web form for a currency exchange demonstration. I have included a snippet of HTML and Javascript code that I have initially implemented. <!DOCTYPE html> <html lang="en"> <head> <meta charset="ut ...

Instance of a Vue.js class that is reactive

I've been developing a worldbuilding app for my initial Vue.js project. Within the app, I've defined various ES6 classes that outline different data types (such as a Project, a Planet, a Star, etc). My goal is to create a sidebar that displays th ...

`initMap` does not exist as a function

Hey everyone, I need some help: I recently integrated the Google Maps API into my AngularJs project and encountered an error in the console: Uncaught message: "initMap is not a function" name: "InvalidValueError" This occurs when the Google Map API is ...

The Axios API request cannot be customized with parameters

I've been encountering an issue where the values I'm trying to pass to my dispatch function are not being recognized and showing up as undefined. It's puzzling because all the values exist and display properly when logged in the component. ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

The ternary operator for checking multiple properties on a JSON object does not seem to be functioning as expected in Node.js, although it works fine

I am facing an issue with a JSON object I have. It looks like this: let obj = { 'key1' : 'value1' , 'key2 : { 'key2a' : 'value2a' } } My goal is to perform a ternary operator check that is equivalent to the fol ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

React's setState() not reflecting state changes when clicked

I have developed a component that displays data from a Redux store grouped by week. To ensure the week's relevance is maintained within this component, I decided to store its value in local state as shown below: constructor(props) { super(props ...

Navigating between two intervals in JavaScript requires following a few simple steps

I have created a digital clock with a button that switches the format between AM/PM system and 24-hour system. However, I am facing an issue where both formats are running simultaneously, causing the clocks to change every second. Despite trying various s ...

The application of textures in Three.js models is not working correctly on the entire object

I am encountering an issue with applying textures on both the top and bottom faces of a surfboard obj file. The texture seems to split in the middle instead of being applied seamlessly across the face, and it also gets applied on the inside of the mesh. I ...

Using Node.js to dynamically load HTML content

I'm just starting out with NodeJs. I'm currently trying to retrieve some HTML from a website to parse it and extract information for debugging purposes. I've had success using the http module (refer to this post), but when I print the ch ...

Changing the name of a specific attribute in a JSON Object for showcasing it in an HTML Table

Suppose I have fetched a list of objects from a database: [{ "id":0 ,"name":"John", "lastname":"Shell" },{ "id":1,...]; and want to display this data using the dynatable plugin: data : JSON.stringify(data) success: function(data,status){ $( ...

Best practices for selecting checkboxes and transferring values to another page in PHP/HTML

Apologies for my lack of experience in PHP. I am in the process of creating a project without any knowledge of PHP. I have set up a database with a list of users and can display users based on specific information through a search. Each search query has a ...

Arranging JSON objects in an array based on date, with the ability to include a 13th month in the date format

I have a function that successfully sorts an array of JSON objects by date, but I need it to also accommodate the 13th month (salary). module = {}; module.exports = [ { "date": "01-2012" }, { "date": "12-2011" }, { ...

Leveraging jQuery and Ajax for extracting and transmitting parameters within href links

Here is my HTML link code: <div id="message"></div> <a href="cats.php?id=60&color=brown&name=kitty" id="petlink"> Click here </a> I want to use jQuery and Ajax to send these parameters when the link is clicked: id=60 colo ...