[英]How do I fetch a backbone.js model from serialized json from a mvc3 model?
[英]How do I view model data after fetch in backbone.js
我是來自strockout.js的骨干新手,我正試圖克服這個簡單的難題。 我有以下代碼:
$(function(){
window.Student = Backbone.Model;
window.Students = Backbone.Collection.extend({
model: Student,
url: 'test.php'
});
window.students = new Students();
window.AppView = Backbone.View.extend({
el: $('#container'),
initialize: function() {
Students.bind('reset', this.render);
},
render: function(){
console.log(Students.toJSON());
}
});
window.appview = new AppView();
$('#test').click(function(){
//var students = new Students();
students.fetch();
var q = students.toJSON();
console.log(q);
/*
students.create({
name: 'John',
grade: 'A'
}); */
})
});
我的服務器發送以下JSON:
[{"id": "1233","name": "Karen","grade": "C"},{"id": "1234","name": "Susan", "grade": "F"}]
當我單擊按鈕並查看Chrome中的控制台時,我看到:
首次點擊:
[] - Corrected -just an empty array
第二次點擊:
[
Object
grade: "C"
id: "1233"
name: "Karen"
__proto__: Object
,
Object
grade: "F"
id: "1234"
name: "Susan"
__proto__: Object
]
第一個問題是為什么需要兩次點擊? 第二:如何簡單地將等級(既作為集合又通過ID)分配/綁定到文本框, <li>
或其他UI元素(最好是在彈出ajax時使其可見)。
您看到的控制台消息來自click事件處理程序。 來自render方法的控制台消息永遠不會被調用。
您不會在第一條日志消息中看到任何內容,因為fetch
是一個異步方法,因此當您在fetch
之后立即調用toJSON
時,尚未從fetch方法中填充該集合。
您需要對代碼進行一些更改才能使其按預期工作。
首先,您需要在實例化視圖時傳遞集合
//original
window.appview = new AppView();
//new
window.appview = new AppView({ collection: window.students });
然后,在視圖中,您需要綁定到傳遞給構造函數的集合上的reset事件。 (您必須綁定到實例化的對象,而不是像最初那樣綁定對象的定義)
window.AppView = Backbone.View.extend({
el: $('#container'),
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('reset', this.render);
},
render: function(){
console.log(this.collection.toJSON());
}
});
現在,在您的click事件中注釋掉控制台日志消息,然后只需單擊一次,您將看到來自render方法的控制台日志消息。
$('#test').click(function(){
//var students = new Students();
students.fetch();
//var q = students.toJSON();
//console.log(q);
/*
students.create({
name: 'John',
grade: 'A'
}); */
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.