After running once, collection functions do not return a function

I am currently working on a project that incorporates Vue components and utilizes the collection design pattern to manipulate lists. Within the collection, there is a function called arr.add that successfully adds a new object to the list when a button is clicked. However, I have encountered an issue where this function works correctly on the initial call but throws an error stating it is not a function when called for a second time. This problem seems to persist across all of my function calls.

Interestingly, if I manually input the data into the list without using the collection method, everything functions as expected. But as soon as I attempt to use the collection for a second time, I receive the following error: Uncaught TypeError: this.exerciseList.add is not a function

Below is the code snippet of the collection model:

function ExerciseCollection(arr = []){

    // Various manipulation functions within the collection
    arr.add = function (exercise, date){
        // Functionality to add exercise with optional date
    }

    arr.delete = function (exercise){
        // Functionality to delete exercise
    }

    arr.deleteSet = function (exercise, set){
        // Functionality to delete specific set within exercise
    }

    arr.addSet = function (exercise){
        // Functionality to add set to exercise
    }
    return arr;
}

The issue seems to arise at the following section where these functions are being invoked:

const app = Vue.createApp({
    // All data for the app, must return an object
    data() {
        return {
            exerciseList: new ExerciseCollection().add({...}),
            dayList: new DayExerciseCollection(),
            reviewList: new ReviewCollection(),
            daysReview:{},
            selectedEditExercise: {},
            currentDay: ''
        };
    },
    methods {
        // Method to add exercise and update day list
        addExercise(exercise, date){
            this.exerciseList.add(exercise, date);
            this.dayList.add(exercise, date);
        },
        ...(rest of the file)

Answer №1

Customizing arrays with additional methods may not be the best approach, as it is not a necessity.

The issue arises from Vue's reactivity which expects arrays to be reactive in the data property and ignores custom methods. In Vue 3, there is support for reactive classes with ES6 classes and prototype methods that alleviate this issue while still having some caveats outlined in this stack overflow thread.

To enable method chaining in Vue, the state of the array needs to be assigned as a field within a class rather than being an instance by itself:


class ExerciseCollection {
  constructor(arr = []) {
    this.list = arr;
  }

  add(exercise, date){
    ...
    return this;
  }
}

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

Maintaining a model when a bound property changes

When it comes to persisting a model immediately, especially when one of its attributes is bound to a template input, the debate arises - should this functionality belong to the model or the controller? In an attempt to address this dilemma, I devised a so ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

Enhance your website with a unique hover and left-click style inspired by the functionality of file explorer

I have a set of items like this: I am trying to replicate the functionality of a file explorer in terms of item selection. To clarify, I aim to create a feature where hovering over an item and left-clicking it would generate a virtual rectangle to select ...

When using Mongoose populate, it may either return an empty array or a list of Object

Currently, I am honing my skills in express.js by constructing a relational API but facing difficulty in populating keys within a schema. The structure involves having a list of properties, each with associated units. The units are linked through a proper ...

The event listener is activated before the HTML element is selected for clicking

I've encountered a strange issue while using the addEventListener method on an HTMLElement within a function that is triggered onload. The problem is that the method seems to be getting executed before I even attempt to click on the element in the HTM ...

Adjust color in real-time with JavaScript

I am using a json file to store data for generating a diagram, and I want to change the color of the diagram conditionally based on an attribute in the json. If the attribute is false, the color should be red, and if true, it should be green. Here is a sni ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

I aim to utilize lodash filter to swap out any null values with zero

let x = [{'abc': 1, 'qwe':2},{'abc': 2, 'qwe':2},{'abc': 5, 'qwe':null}, {'abc': 4, 'qwe':null}], let result = _.chain(x) _.groupBy(qwe) _.map ...

Tips for utilizing a primary template within a secondary container

In my code snippet below, I have outlined two steps: "step===1" and "step===2". My goal is to reuse the step 1 template for step 2. This means that after completing step 1 and clicking on the next button, I want to show the same template again for reusabil ...

Guide on utilizing a map with both String and double values within the Struts 2 framework

I have a question about passing a HashMap with String and double values from an Action to JavaScript code. How can this be achieved? When editing fields with double values, I encounter null values on those fields. What is the best way to resolve this issu ...

The ng-class directive is not functioning properly when used in conjunction with $scope.$watch on the second click

Hey there, I've encountered an issue with my code. Everything works smoothly when toggling the checkbox using ng-click and dynamically updating it based on input numbers in the input tag through $scope.$watch(). However, when I try to uncheck the &apo ...

Pattern to prevent consecutive hyphens and identical digits next to one another in a series

Here is a regular expression that can validate all numbers not being the same even after a hyphen: ^(\d)(?!\1+$)\d{3}-\d{1}$ For example, in the pattern: 0000-0 would not be allowed (all digits are the same) 0000-1 would be allowed 111 ...

Guide: Enhancing Query Context within jQuery Instances Spanning Across Iframes

In my current project, I am facing a challenge with using a jQuery instance across iframes. It's been causing me quite a bit of frustration. Here's the situation: I have an existing web application that loads jQuery (which is aliased as $jq) in ...

Using Twitter's typeahead along with Bloodhound for handling JSON objects

I've been struggling to make it work with JSON objects. Despite trying various solutions found on SO, none of them have worked for me. $(function() { var items = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name&ap ...

Is there a way to automatically create distinct DOM ids every time?

As I delve into coding with JS and the DOM, I frequently encounter the need to create ids (or names) solely for the purpose of grouping DOM elements together (or associating them with each other)1. These ids (or names) are not referenced anywhere else in ...

Can the CSS of an iframe be modified if the iframe is located on a different domain?

Is it feasible to modify the CSS of an iframe if the iframe is not located on the same domain? If so, what are some ways to apply and alter CSS for this situation? Any assistance would be greatly appreciated. <iframe id="frame1" width="100%" height="35 ...

Tips for sorting through objects based on their properties within an array in Angular

I'm facing an issue with displaying the title of a specific object in an array by filtering. Here's what I tried: <p>{{ element | myFilter:'type':'Type1').title }}</p> After creating a pipe filter like this: impor ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Having trouble locating node_modules/nan on your system?

Trying to globally install this project is proving to be a challenge as I run the command npm i -g. Followed these steps: git clone https://github.com/superflycss/cli cd cli npm i npm i -g However, encountered this result: ole@mki:~/cli$ npm i -g npm W ...

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...