View's backbone is attuned to the model's every event

I'm struggling with the communication between Backbone view and model. The view should be able to listen to events from the model, and function couponReader is expected to retrieve data from the model and add it to the cart after confirmation. Any assistance would be greatly appreciated.

define([
'jquery',
'underscore',
'backbone',
'text!templates/menu/menu.html',
'text!templates/menu/cartItem.html',
'collections/cart',
'views/menu/topBar',
'models/coupon',
'swipe'

], 
function ($, _, Backbone, menuTemplate, cartItemTemplate, Cart, TopBarView, Coupon)  {

var slider;
var sliderPosition = 0;
var top;

var menuView = Backbone.View.extend({
    el:$("body"),

    events:{
        "click #keno50":"addKeno50",

    },

    initialize:function () {

        this.couponReader();
    },

    render:function () {
        this.el.html(menuTemplate);
        // TODO - Memory leak here :O
        new TopBarView({ el: this.$('#topBar') }).render();
        this.slider = new Swipe(document.getElementById('slider'), {startSlide:sliderPosition});
        this.resizeScreen();
        return this;
    },

    couponReader:function () {
        var coupon = new Coupon({   //issue here
            name: Coupon.getCoupon().name,
            price: Coupon.getCoupon().price
        });
        Cart.add(coupon);
    },


    addKeno50:function () {
        var keno50 = {
            name:"Keno",
            price:50
        }
        Cart.add(keno50);
        sliderPosition = this.slider.getPos();
        this.render();
    }

});
return new menuView;
});

model class: it listens to the server in loop, get data from server whenever a data is loaded.

define(['jquery', 'underscore', 'backbone'],
function ($,_, Backbone) {
    var Coupon = Backbone.Model.extend({
        initialize:function () {
           this.getCoupon(); //console.log("funkar*?");
        },
   getCoupon : function() {
        var XHR = this.getRequest();
    XHR.done(function(data){
        var keno10 = {
            name: data.description,
            price: parseInt(data.price)}

        var price = parseInt(data.price);
        var name = data.description;
        var status = data.ok;
    })
    },

    getRequest:function() {
        var fn = arguments.callee;
        var XHR = $.ajax({
            url: '/nextdocument',
            type: 'GET',
            async: true,
            cache: false,
            timeout: 11000, //vänta på svar från servern om ingen inläsning
            success:function(data) {
                var name = data.description;
                var price = data.price;
                console.log("read--> " + name + price);
                setTimeout(fn, 1000);
                if (data.ok == "true") {
                    data["ok"] = data.ok;
                    $.ajax(
                        {
                            url: "/customerdone",
                            data: JSON.stringify(data),
                            processData: false,
                            type: 'POST',
                            contentType: 'application/json'
                        }
                    )
                }else{
                    //no document if no read in
                    console.log("error--> " + data.errorMessage)
                }
            }
        })
        return XHR;
    }

    });
    return Coupon;
});

Answer №1

Upon examining your instance, I have identified a couple of problematic areas.

  1. The menuView does not bind to any Coupon events, therefore it will not be aware of any events dispatched by the Coupon.

  2. You can specify a URL for your model and leverage Backbone's fetch() method to retrieve data instead of manually adding an Ajax call.

    initialize: function () {
      this.coupon = new Coupon();
      this.coupon.bind('change', this.couponCreated, this);
      this.coupon.fetch();
    },
    couponCreated: function () {
      Cart.add(this.coupon);
    }
    
  3. It appears that you are making multiple ajax calls to acquire the same data. For example, within menuView.couponReader(), two instances of new Coupon() and Coupon.getCoupon() are created, resulting in redundant Ajax calls as currently configured.

Your intentions in the provided code were somewhat unclear. It seems like you are attempting to fetch a new Coupon upon creation of the menuView and add it to the Cart. In such cases, consider exploring the URL/fetch() approach mentioned earlier. By utilizing a callback, you can avoid the need to listen for events. The issues you are encountering likely stem from asynchronous problems, where the Coupon is added to the Cart before the Ajax call returns with the necessary data.

    couponReader: function () {
      var self = this
        , coupon = new Coupon();
      coupon.fetch({success: function (model, response) {
        Cart.add(model);
      });
    }

Alternatively, you could perform a fetch() without a callback and instead listen for the 'change' event as suggested in point #2 previously.

Please note: both approaches rely on using Backbone's data synchronization mechanism through the Model's url property.

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

Struggling to receive information from a third-party API using a token in a React application

Currently, I am attempting to retrieve data from a third-party API. While it functions properly on Postman, I am striving to successfully make a request and access the data within my React project. The public API in question is: https://api.securityscorec ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Make sure to adjust the original router URL when the application is being run within iframe or object

Currently, I am embedding Vue apps within object tags or iframes of a master Vue app container. Initially, I set up a file server that serves the container or the requested sub-app to render inside a div. Below, I will show the necessary routing of my Nod ...

What is the method for selecting multiple items from a list?

Is it possible to select multiple items in the image above? I attempted using http://ionicframework.com/docs/components/#checkbox, but I prefer having checkboxes for multiple selections in Ionic. I am currently working with the Ionic framework and would a ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

The database was successfully updated; however, the API encountered a 500 error when trying to access

Currently, I am working on a project that utilizes Javascript alongside Node.js, Express, SuperAgent, and KnexJS for database management with Sqlite3. The issue I am facing is as follows: Upon submitting data for updates through my API route using the PUT ...

What are the key indicators to differentiate between JavaScript and CSS code within a string?

I am faced with the challenge of receiving strings of code through simple POST requests. I am seeking a smart method to differentiate between JavaScript and CSS scripts without executing the script itself. My confidence level in distinguishing them accurat ...

Saving dynamically generated variable values in a MySQL database using PHP: A step-by-step guide

Need help saving data from dynamically generated checkbox, label, and select tags into a MySQL database using PHP. The goal is to store the checked field with its corresponding label value and selected option value. However, encountering difficulties in ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Guide for implementing pagination on a lengthy list with React MaterialUI

I'm currently working on a project using react and MaterialUI to create a list with filter functionality. The list will be populated with data from an Http request and may contain a large number of items. I was researching pagination in the MaterialUI ...

Is it possible that ngChange does not trigger when the model is updated through code?

According to the documentation, the ngChange directive will not trigger if the model is updated programmatically rather than through a change in the input value. Does this imply that once you programmatically modify the model, you are unable to utilize ng ...

The type 'VueClass<Vue>' cannot be assigned to the Apollo parameter

I am currently in the process of developing a 'Nuxt.js' application using typescript. Below is the code snippet I am working with: <script lang='ts'> import {Component, Vue} from 'nuxt-property-decorator'; impor ...

"Exploring Umbraco's path to integrating with Angular for seamless

I have encountered an issue in my Umbraco web application where I have two SPA angular applications on pages /pageOne and /pageTwo. Whenever these pages are refreshed, a page not found error occurs due to Umbraco's routing system. Is there a way to r ...

Combining Vue properties with predefined defaults

In my Vue component, I am utilizing an options prop with a predefined default value. export default { props: { options: { required: false, type: Object, default: () => ({ someOption: false, someOtherOption: { ...

Local email.js functionality successful, but fails upon deployment alongside React

I have implemented Email.js to create a contact form for a Next.js website. It functions perfectly when tested locally, but encounters issues once deployed. Upon clicking the submit button, the form fails to reset as intended within the sendEmail function. ...

Tips for eliminating elements from an array and incorporating the modified array in the initial for loop

Utilizing NodeJS, Express, Passport, and a MongoDB database, I have been working on sorting an array by comparing each element with the previous one. If they match, I remove the duplicate from the array. However, after processing, the original array and th ...

What is the best way to prompt users to rotate their mobile phone using javascript/css?

My website is designed to be viewed horizontally only, but I am struggling to block access if the user tries to view it vertically. I can't seem to figure out how to do this on my own. Is there anyone who can offer guidance or assistance? ...

The function is coming back with a value of undefined

I need some assistance with a function I have below. This function is meant to download files one by one and move them to a directory called templates. At the end, it should return the length of the directory. However, it seems to be returning an undefined ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Creating an exportable class in Typescript and Node.js is a crucial aspect of

I've encountered an issue while trying to create a separate class file for import from the controller. It seems that declaring variables inside the class is not working as expected. Below is the class I intend to export: const fs = require("fs&q ...