0

I have a JSON that returns from a REST API the following :

[
    {
        title: "Block 1",
        images: [url1, url2, url3]
    },
    {
        title: "Block 2",
        images: [url7, url8, url9]
    },
    {
        title: "Block 3",
        images: [url4, url10]
    }
]

On the view I want to render URLs so I can show the images on the template, for that I have the below :

index.html

<script id="template" type="text/template">
    <img src=<%= images %>>
</script>

Main.js

theView = Backbone.View.extend({
    el: $('#mydiv'),
    render: function() {
        var template = _.template($('#template').html());
        var html = template(this.model.toJSON());
        this.$el.html(html);
        return this;
    }

})

fetchFromServ = Backbone.Model.extend({
    url: "http://example.com/jsonFile.php"
})

document.addEventListener('DOMContentLoaded', () => {

    var fet = new fetchFromServ();
    foo = fet.fetch();

    var view = new theView({ model: foo });
    view.render();

});

So far, here is what I get :

Uncaught TypeError: this.model.get is not a function
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Folky.H
  • 1,164
  • 4
  • 15
  • 37

1 Answers1

1

Use var (or ES6 variants let or const) so you won't always create implicit globals.

var foo = fet.fetch();

fetch returns a jqXHR because it calls jQuery.ajax in the background, it doesn't return the model.

So you should instantiate your view with fet instead.

var view = new theView({ model: fet });

Also, a good convention is to capitalize "types" variable, like TheView or FetchFromServer.


You could replace document.addEventListener with jQuery's shorthand $(() => {}) since you're already using jQuery.


Note that your template won't work with the current data you've provided.

You'd need to loop through the images URL array and output an img tag for each. For this, you should use a Backbone Collection to handle the received data.

There are already a ton of examples, tutorials, and many other answers which explain how to render a list. Here's a few of my own:

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129