The method xxx is not defined within my ViewModel

Why am I encountering an error

Uncaught TypeError: this.createRow is not a function
when constructing the matrixLengthsAvailable array?

The createRow function is defined at the end of my viewmodel...

function TabBuyHarvesterModel() {
    self = this;

    this.selectedEmote = ko.observable('kappa');
    this.matrixLengthsAvailable = ko.observableArray([
        { length: 10, pctDetails: this.createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
        //30,
        //60,
        //180,
        //360,
        //720,
            //1440
        ]);

    this.selectEmote = function (emoteClicked) {
        self.selectedEmote(emoteClicked.emote);
    };

    this.createRow = function (rowLength) {
        var ret = new TabBuyHarvesterMatrixRowModel();
        ret.rowLength(rowLength);
        return ret;
    };
}

Answer №1

It is advisable to utilize the 'self' method as suggested and ensure its correct implementation throughout your code. Additionally, make sure to reorganize the order of methods so that 'createRow' is declared prior to its usage.

To view the example, visit: http://jsfiddle.net/oshmn46o/

function TabBuyHarvesterModel() {
var self = this;

self.createRow = function (rowLength) {
    var ret = new TabBuyHarvesterMatrixRowModel();
    ret.rowLength(rowLength);
    return ret;
};

self.selectedEmote = ko.observable('kappa');
self.matrixLengthsAvailable = ko.observableArray([
    { length: 10, pctDetails: self.createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
    //30,
    //60,
    //180,
    //360,
    //720,
        //1440
    ]);

self.selectEmote = function (emoteClicked) {
    self.selectedEmote(emoteClicked.emote);
};

}

Answer №2

When utilizing ko.observableArray(), the reference to 'this' in this.createRow will point to the context of the observableArray. It is advisable to replace 'this' with 'self' for clarity and consistency.

Answer №3

It seems like you're attempting to call the createRow function before it has even been defined. To avoid this issue, make sure to define createRow before matrixLengthsAvailable. A more efficient approach would be to define the createRow method on the prototype of TabBuyHarvesterModel. By doing so, the function will only be declared once, ensuring it is available before any instances of your class are created.

function TabBuyHarvesterModel() {
    ...
}

TabBuyHarvesterModel.prototype.createRow = function (rowLength) {
    var ret = new TabBuyHarvesterMatrixRowModel();
    ret.rowLength(rowLength);
    return ret;
};

Answer №4

It is recommended to only reference the function createRow from within the scope of TabBuyHarvesterModel. By making it a regular function, you can avoid the need to define createRow before the observable matrixLengthsAvailable. JavaScript automatically hoists functions to the top of a closure, even if they are not initially defined at the beginning of the closure:

function TabBuyHarvesterModel() {
    self = this;

    this.selectedEmote = ko.observable('kappa');
    this.matrixLengthsAvailable = ko.observableArray([
        { length: 10, pctDetails: createRow(10) /*ko.mapping.fromJS({ rowLength: 10 })*/ }
        //30,
        //60,
        //180,
        //360,
        //720,
            //1440
        ]);

    this.selectEmote = function (emoteClicked) {
        self.selectedEmote(emoteClicked.emote);
    };

    function createRow(rowLength) {
        var ret = new TabBuyHarvesterMatrixRowModel();
        ret.rowLength(rowLength);
        return ret;
    }
}

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

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Having difficulties in loading the CSS file for my real-time chat application built with Express and Socket.io

Hi everyone, I've been struggling with an issue for the past couple of days where I can't seem to load my CSS for my Express app. If anyone has a solution, I would greatly appreciate the help. Below is my server.js code: const express = requir ...

"Integrating auto-expandable rows and subrows into a React table with the use

Presented here is my code for a React table using hooks. I encountered a challenge when trying to set all rows and subrows to be expanded by default upon opening the page. Despite attempting various solutions, none of them proved successful. Check out the ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

Guide on how to execute jasmine tests coded in TypeScript for Node.js applications

I am eager to test my express application developed in TypeScript. I am utilizing jasmine for writing test cases, webpack for bundling TypeScript files to JavaScript, and karma as the test runner. Please locate the following files: // about.service.ts - ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

Determine ng-checked according to an array

I am working with a select dropdown that creates checkboxes using ng-repeat based on the selected value. The goal is to have all values in the dropdown selected, corresponding checkboxes checked, and store them in an array. Each time a checkbox is changed ...

Strapi: Enhancing User Experience with Unique Passwordless Customization Services

I have been attempting to modify the "passwordless" strapi plugin in order to generate verification codes consisting exclusively of digits. To achieve this, I need to override the createToken function within the plugin's service. Following the instru ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

AngularJS handles intricate JSON responses effortlessly

I have been learning angularjs on my own, mostly from w3schools and other websites. I have been trying to download and parse some JSON data. I was successful with a simple JSON url (http://ip.jsontest.com), but I am struggling with a more complex response. ...

Adding data to a URL using jQuery Ajax

I'm currently working on implementing Ajax with jQuery and I have a specific requirement to add data to the URL. Take a look at the code snippet below: var my_website= mysamplesite.com/viewData/"; function displayData(myData) { $.ajax({ t ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Tips for updating a single parameter with vue router-link

I am facing an issue with my user list and calendar components. Whenever I click on a user link, I want only the selectedUser parameter in the URL to change while leaving all other parameters unchanged. Currently, when I click on the "Change date" link, i ...

How can I ensure that the scripts returned in HTML via AJAX are executed when using $.load()?

I have been trying to make an AJAX call and receive a partialView which contains some script that needs to be executed. I did some research and learned about the "eval" method, but then discovered that the $.load() method should handle this for me. Howeve ...

Implementing a Custom HTML Attribute to the Script Tag in Vue JS

I have decided to switch from using Google Analytics to Plausible analytics for my website. However, I am encountering an issue with adding the Plausible script to the head of my Nuxt JS document. I have created a custom plugin to handle this, but the Vue ...

Ways to extract tar data from a hexadecimal representation

After making a RESTAPI call to an endpoint, I was expecting to receive .tar contents. However, what I received appears in hexadecimal format as: <Buffer 4d 4d 00 2a 00 00 00 08 00 13 01 00 00 03 00 00 00 01 01...... The function connectForTar demonstra ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

In search of a way to verify if a string contains a specific word

I'm currently working on a dynamic tooltip feature. My goal is to detect multiline tooltips by checking if my data includes \r. The code snippet below is an example of how I am trying to analyze my description, but so far, I have been unsuccessfu ...

"Is it possible to include a query in a reducer with

Hey, how can I implement this inside a reducer to modify the state's value? doc = { id:"zf123ada123ad", name:"examp", subdoc:{ name:"subdoc examp", subsubdoc:[{ id:"zcgsdf123zaar21", subsubsubdoc:[{ ...