Question

I'm using backbone.js and Lithium. I'm fetching a model from the server by passing in a _id that is received as a hidden parameter on the page.

The database MongoDB has stored the data correctly and can be viewed from console as:

{ "_id" : ObjectId("50bb82694fbe3de417000001"), "holiday_name" : "SHREE15", "description": "", "star_rating" : "3", "holiday_type" : "family", "rooms" : "1", "adults" : "2", "child" :"0", "emails" : "" }

The Lithium Model class is so:

class Holidays extends \lithium\data\Model {
public $validates = array(
        'holiday_name' => array(
                array(
                        'notEmpty',
                        'required' => true,
                        'message' => 'Please key-in a holiday name! (eg. Family trip for summer holidays)'
                ))); }

The backbone Holiday model is so:

    window.app.IHoliday = Backbone.Model.extend({       
    urlRoot: HOLIDAY_URL,
    idAttribute: "_id",
    id: "_id",
    // Default attributes for the holiday.
    defaults: {
    },

    // Ensure that each todo created has `title`.
    initialize: function(props) {

    },

The code for backbone/fetch is:

var Holiday = new window.app.IHoliday({ _id: holiday_id });
        Holiday.fetch(
                {
                    success: function(){
                        alert('Holiday fetched:' + JSON.stringify(Holiday));
                        console.log('HOLIDAY Fetched: \n' + JSON.stringify(Holiday));
                        console.log('Holiday name:' + Holiday.get('holiday_name'));
                    }
                }               
           );

Lithium Controller Code is:

public function load($holiday_id)
{
    $Holiday = Holidays::find($holiday_id);
    return compact('Holiday');
}

PROBLEM: The output of the backbone model fetched from server is as below and the Holiday model is not correctly 'formed' when data returns into backbone Model:

    HOLIDAY Fetched: 
{"_id":"50bb82694fbe3de417000001","Holiday":{"_id":"50bb82694fbe3de417000001","holiday_name":"SHREE15","description":"","star_rating":"3","holiday_type":"family","rooms":"1","adults":"2","child":"0","emails":""}}

iplann...view.js (line 68)

Holiday name:undefined

Clearly there is some issue when the data is passed/translated from Lithium and loaded up as a model into backbone Holiday model. Is there something very obviously wrong in my code?

Was it helpful?

Solution

By default, Backbone expects the model data at the root of the response. You are putting it under the "Holiday" key. In your controller, try return $Holiday->to("array");. That should return it as Backbone expects. Alternately, you can override your Backbone model's parse() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top