1

我正在使用backbone.js 和锂。我通过传入作为页面上隐藏参数接收的 _id 从服务器获取模型。

数据库MongoDB已正确存储数据,可以从控制台查看为:

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

锂模型类是这样的:

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)'
                ))); }

骨干假日模型是这样的:

    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) {

    },

主干/获取的代码是:

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'));
                    }
                }               
           );

锂控制器代码是:

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

问题:从服务器获取的主干模型的输出如下,当数据返回到主干模型时,假日模型没有正确“形成”:

    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

显然,当数据从 Lithium 传递/转换并作为模型加载到主干假日模型中时,存在一些问题。我的代码中有什么非常明显的错误吗?

4

1 回答 1

1

默认情况下,Backbone 期望模型数据位于响应的根目录。你把它放在“假期”键下。在您的控制器中,尝试return $Holiday->to("array");. 这应该像 Backbone 期望的那样返回它。或者,您可以覆盖 Backbone 模型的parse()方法。

于 2012-12-02T17:44:39.490 回答