Having trouble invoking an already existing function from a template rendered by underscoreJS

In my Backbone / Underscore app, I have successfully rendered one template and implemented a method call "onclick" of a button. This function smoothly renders another template that contains another method call "onclick" for a button.

  • #showTransportsTemplate: initial template with a "transport" model passed to it
  • bookTicket(tid): a function that fetches the associated transport model using "tid" from the collection and sets them into a "booking model" passed on to the second template
  • #confirmBookingTemplate: second template
    • confirmBooking(): a method that is not recognized or called as expected

Here's the relevant part of app.js:

function bookTicket(tid)
{
    alert("received tid: "+tid);
    var transport = transportList.findWhere({id:tid});
    console.log(transport);



    var newBooking = new Booking();
    newBooking.set('id',"b"+getBookingId());
    newBooking.set('mode',transport.get('mode'));
    newBooking.set('source',transport.get('source'));
    newBooking.set('destination',transport.get('destination'));
    newBooking.set('date',transport.get('date'));
    newBooking.set('class',transport.get('class'));
    newBooking.set('rate',transport.get('rate'));

    var confirmBookingTemplate = _.template($('#confirmBookingTemplate').html(), {booking: newBooking});
               alert(confirmBookingTemplate); // for testing purposes


                $(confirmBooking.el).show();
                 $(confirmBooking.el).html(confirmBookingTemplate);                 
}

function confirmBooking()
{
    alert("confirmBooking"); // no further code written coz this function is not getting called
}

The two templates:

<script type="text/template" id="showTransportsTemplate">

            <table border="1">

                <tr>

                <th> Source </th>
                <th> Destination </th>
                <th> Date Available </th>
                <th> Class </th>
                <th> Rate </th>
                <th> Book </th>
                </tr>



                <% _.each(selTransports, function (transport) {  

                    var myid= transport.get("id");

                %>

                <tr>

                        <td align="center"> <%= transport.get("source") %> </td>
                        <td align="center"> <%= transport.get("destination") %> </td>
                        <td align="center"> <%= transport.get("date") %> </td>
                        <td align="center"> <%= transport.get("class") %> </td>
                        <td align="center"> <%= transport.get("rate") %> </td>
                        <td> <input type="button" onclick="bookTicket('<%= myid %>')" value="Book"> 
                         </input>
                        </td>
                        <td> <%= myid %> </td>
                    </tr>
                  <%
                        });

                    %>

            </table>
        </script>

        <script type="text/template" id="confirmBookingTemplate">
             <br /><br />
            <h3> Booking Details </h3>

... [The remaining HTML code is omitted for brevity] ...

</script>

When testing in Chrome, I encountered an error stating "object is not a function", while Firebug specifies that "confirmBooking()" is not a recognized function although it already exists in the script.

Answer №1

When using Underscore's template function, it utilizes a javascript with block for evaluating templates. This means that any "unqualified names" are assumed to be part of the data object passed into the template method. However, if the name like confirmBooking is not included in that object, the template won't be able to locate it.

If you do need to call a global function from within your template (although it's advised to avoid defining functions in the global namespace), you can explicitly reference the window object. Here's an example:

window.someGlobalFunction = function() {
    return "It worked!";   
}

<script type="text/template" id="template">
    <%= window.someGlobalFunction() %>
</script>

An example demonstrating this: http://jsfiddle.net/dmillz/pqjtR/

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

Component for liking items built with VueJs and Laravel

I'm currently delving into the world of VueJS, and for my personal project, I'm pairing it with Laravel 5.7. However, I'm facing a bit of a challenge when it comes to implementing a simple feature - a "like" button/icon. Here's the sce ...

How to send variables to a method in a JavaScript modular pattern

I am trying to achieve something similar to the code snippet below. However, it seems to be invalid as it does not allow passing variables, specifically 'min' and 'max' in this case. Is there a way to achieve this functionality? If so, ...

Checkbox Trouble: Troubleshooting AJAX Integration

One of the requirements I have is to implement a checkbox list that updates the page via AJAX when one of the checkboxes is clicked. $(document).on("click", ".selectlist input", update_results); My client has requested that one of the checkboxes be pre-s ...

Enhancing the visual appeal of my PLY file with vibrant hues using three.js

Hello everyone, I've run into a little issue with three.js. I'm trying to color a ply file and need some assistance. Specifically, I want to add red coloring to the eyes only, not any other part of the model. Can anyone help me with this using th ...

How to eliminate quotation marks from a nested array in JavaScript

Is there a way to eliminate double quotes from nested array information? ["[a,b,c],[b,c,d],[e,f,g]"] Transforming it into this array: [[a,b,c],[b,c,d],[e,f,g]] through the utilization of javascript ...

Exploring the usefulness of `bind(this)` within a ReactJS constructor

I have a good understanding of the Javascript function bind. However, I'm puzzled by why in the React.js snippet below, this is being bound again to itself. Is this related to the constructor, as this in the constructor can vary depending on how it&ap ...

When a specific string is found in a textbox, trigger a function in JavaScript

Is there a way to search for a specific string within a large text box that contains 200 words? I would like to create a function that can color the string. For example, if the sentence "my dog is happy" is in the textbox and I want the word "dog" to be ...

Tips for employing the slice approach in a data-table utilizing Vue

I have a unique situation in my Vue app where I'm utilizing v-data table. The current display of data in the table works fine, but I now want to enhance it by incorporating the slice method. Here is the current data displayed in the table: https://i ...

issue in jquery: ajax promise not returning any value

My code snippet: var testApp = (function($){ var info = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function fetchInfo(opt) { return new Promis ...

Utilize Mongodb's $in operator to retrieve results in the exact sequence as presented in the array

My challenge involves working with an array that contains Id of a MongoDB collection. array = [ '573163a52abda310151e5791', '57358e5dbd2f8b960aecfa8c', '573163da2abda310151e5792' ] I need the result in the ...

JavaScript Error: Unable to execute getJsonData due to function not found

I am encountering an issue with a function that retrieves JSON data from a URL Here is the code snippet: var retrieveJsonData = function(uri,callback){ $.ajax({ type: "GET", dataType: "jsonp", url: uri, jsonpCallback: 'r ...

Obtain the value of a dynamically selected option

I am facing an issue with my select options where I want the input field to be automatically filled with the 'data-place' value of the selected option whenever it changes. This includes a few dynamic select options. $(function() { // Hand ...

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

Keycloak Node is still prompting for login even when a bearer token is provided

After numerous attempts to integrate Keycloak into my node/express server for bearer token authentication, I find that every protected request I make returns an HTML login page. Here is a snippet of my simple index.js file: const express = require(&a ...

Enhancing the understanding of JavaScript error messages

In my code, I am reading the contents of a file, expecting it to be JSON, parsing it, and printing out the result: 'use strict'; const fs = require('fs'); const Promise = require("bluebird"); Promise.promisifyAll(fs); const printFile ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResul ...

Automated library that refreshes the webpage instantly upon any server modifications

Seeking a Javascript solution to automatically refresh a webpage when the server version is updated. Update: I am aware of the technical aspects involved and how to implement this feature. However, I am interested in finding an existing solution that I ca ...