Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

Backbone fetch an object

I have an app in backbone. In this app I fetch a json stored into my server. For some reason now I don't want to fetch json from file but from an array (same structure that Json) passed from PHP. Ho can I change my code to do the same thing? This is my app

var CombinationView = Backbone.View.extend({ 
    template: _.template($("#hotel-list-template").html()),
    initialize: function(){ 
        this.list = new HotelCollection([], { 
            url: 'includes/list.json' 
        }); 

        this.list.on("sync", this.listLoaded, this); 

        this.list.fetch(); 
    }, 
    render: function(){ 
        this.$el.html('Loading...'); 
        return this; 
    }, 
    listLoaded: function(){ 
        //code
    }
});

The var that I have stored into php is $list_object

How can I change my code to fetch object instead of a url?

Upvotes: 2

Views: 270

Answers (1)

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

Well you can't access PHP variables from javascript. After fetching some informations, the php side already finished its job. There are 2 ways to do whatever you are trying to do.

Create a collection: http://backbonejs.org/#Collection

The collection will fetch the list of objects as JSON. Each object will then be passed to a Model class. This way, you can fetch a list of objects and from this list you can create new models. Since models aren't going to get fetched using sync. A change event should be triggered.

The other thing you can do is to fetch specific objects. When specifying an object, it will send an ID to the php server. With this id, you can load a specific element in the list and parse it as JSON.

Again, from JS, you can only get files from a server or streams. Websocket is the only way to get long lived full duplex socket in javascript.

Upvotes: 2

Related Questions