我正在使用backbone.js和Lithium。 我通过传入一个在页面上作为隐藏参数接收的_id从服务器获取模型。
数据库MongoDB已正确存储数据,可以从控制台查看:
{ "_id" : ObjectId("50bb82694fbe3de417000001"), "holiday_name" : "SHREE15", "description": "", "star_rating" : "3", "holiday_type" : "family", "rooms" : "1", "adults" : "2", "child" :"0", "emails" : "" }
Lithium Model类是这样的:
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模型未正确“形成”:
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传递/转换数据并将其作为模型加载到骨干假日模型时存在一些问题。我的代码中有一些非常明显的错误吗?
答案 0 :(得分:1)
默认情况下,Backbone期望模型数据位于响应的根部。你把它放在“假日”键下。在您的控制器中,尝试return $Holiday->to("array");
。这应该像Backbone期望的那样返回。或者,您可以覆盖Backbone模型的parse()
方法。