Retrieving data attributes from model within a Backbone view using Underscore template

I have a Backbone.js view that I'm working with:

var StreamV = Backbone.View.extend({
    tagName: 'div',
    className: 'stream',
    events: { },
    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
    },
    render: function () {
        this.$el.html(this.template(this.model.attributes));
        return this;
    },
    template: function (data) {
        console.log(data);
        if (data.mime_type.match(/^audio\//)) {
            return _.template('<audio controls><source src="<%= resource_uri %>">No sound</audio>', data);
        } else {
            // FIXME Do what?
            return _.template();
        }
    },
});

Along with the model associated with it:

var StreamM = Backbone.Model.extend({
    url: function () {
        return (this.id) ? '/streams/' + this.id : '/streams';
    }
});

To create an instance of the StreamV view, I do the following:

$(document).ready(function () {
    var streams = new StreamsC;
    streams.fetch({success: function (coll, resp, opts) {
        var mp3 = coll.findWhere({mime_type: 'audio/mp3'});
        if (mp3) {
            var mp3view = new StreamV({el: $('#streams'),
                                       model: mp3});
            mp3view.render();
        } else {
            $('#streams').html('No audio/mp3 stream available.');
        }
    }});
});

However, when passing data to my Underscore template, I encounter the following error:

ReferenceError: The variable resource_uri is not defined
  ((__t=( resource_uri ))==null?'':__t)+

I've attempted to include a literal object with the resource_uri property in the _.template call but still face the same issue.

Is providing an object as the second argument to _.template the correct approach?

Answer №1

The Underscore template function provides a way to return a function that can be invoked with data at a later time. The second argument of this function is not the actual data to be inserted, but rather a settings object.

According to the documentation for Underscore:

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

In your scenario, you would first compile the template like this:

this.compiledTemplate = _.template('<audio controls><source src="<%= resource_uri %>">No sound</audio>');

Then, when you are ready to render the view, you would call this function with the necessary data:

this.$el.html(this.compiledTemplate(this.model.toJSON()))

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

Unable to update state from within a function in react

As I delve into the realm of coding, a simple graph catches my eye. It showcases various data sets including current, all, and filtered data. Initially, the first block of code runs smoothly. However, upon attempting to setState in order to make some modif ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Is there a way to modify the domain of an iFrame's scr based on the parent window's URL?

Is there a way to dynamically change the scr="" attribute of an iFrame based on the current URL of the window? The goal is to have different values for the scr attribute depending on the parent window's URL. For example, if the parent window's UR ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

Ensuring that the empty bubble remains undisturbed, here's a guide on effectively implementing the if

I need assistance with adding an "if condition" to my text field. The condition should prevent the empty bubble from appearing when the send button is clicked. function verifyInput(){ var currentText = document.getElementById("demo").innerHTML; var x ...

What is the best way to disengage a loop of elements within an internship?

In my scenario, the DOM structure is as follows: <table id="campaigns"> <tr> <th>Name</th> <th>Status</th> </tr> <tr> <td>first data</td> </tr> <tr data- ...

Managing object methods in ReactJS state

Currently, I am utilizing the Google Maps API and have the following piece of code implemented: class App extends React.Component { state = { polygon: null, }; checkPoly() { if (this.state. ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

How to italicize a portion of output using JavaScript

There are numerous inquiries on the internet and on this site regarding how to make italic fonts, however, none specifically address how to italicize only a section of a string. In my scenario, I have a form where I input the book title, author's nam ...

Material UI Grid's layout does not support placing a select element within a row

As a newcomer in the world of full stack development, I am delving into coding projects to enhance my understanding of frontend technologies like React JS and Material UI. My latest endeavor involves creating a page that displays posts from the backend in ...

Tips for ensuring an element is visible in CUCUMBER JS?

Whenever I run my code, it keeps returning the error message: NoSuchElementError: no such element: Unable to locate element Even though I have set up a wait function, it does not seem to actually wait. The step fails immediately without waiting for the s ...