Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - fetch data and display

Tags:

backbone.js

I'm just beginning out on Backbone.js. Here's my code.

$(function(){

    //Backbone Model
    var Cat = Backbone.Model.extend({});

    // create a collection
    var CatCollection = Backbone.Collection.extend({
        model: Cat,
        url: 'http://localhost/cats/index.php/cats/index'
    });
    var catCollection = new CatCollection();
    catCollection.fetch();

    // Backbone view
    var CatView = Backbone.View.extend({
        el: $("#contents"),
        initialize: function() {
            this.render();
        },
        render: function() {
            this.el.html(catCollection);
        }
    });

    var catView = new CatView();
});

What I am doing is.

  1. Create a backbone model
  2. Create a collection using the model I created.
  3. Fetch data from MySQL database - this returns a JSON data object.
  4. Display the fetched data in the div "#contents".

On google Chrome, I can see that the "fetch()" method works, because I can see my JSON object returned as

[{"id":"1","name":"stella","age":"5"},{"id":"2","name":"Max","age":"2"}]

But if I do "alert(catCollection)" after the fetch, it displays "[object] [object]".

What is the best way of displaying this?

like image 648
ericbae Avatar asked Aug 12 '11 04:08

ericbae


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is Backbone JS frontend or backend?

Front-End MVC frameworks (Backbone, Angular, etc) all rely on a backend service to provide the data that, say Backbone, would then use as its model. You could have an entire MVC pattern on the backend that accepts requests and spits out some JSON for a frontend MVC framework to use.

What is backbone JS comparable to?

Vue. js, React, AngularJS, Angular 2, and Ember. js are the most popular alternatives and competitors to Backbone. js.

Is backbone a MVC?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.


2 Answers

You should use the templates in JST array.

$(this.el).html($(JST["comments/item"](model.toJSON())));

"comments\item" is the template path and name If you are using Rails, just use the Jammit and write templates with ERB (default) or Jade

like image 119
skayred Avatar answered Nov 01 '22 21:11

skayred


The backbone.js documentation give an example like so:

alert(JSON.stringify(catCollection));

http://backbonejs.org/#Collection-toJSON

like image 24
Justin Geeslin Avatar answered Nov 01 '22 21:11

Justin Geeslin