如何在backbone.js中获取后查看模型数据

Len*_*Len 0 javascript backbone.js

我对来自knockout.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'
        }); */
    })
});
Run Code Online (Sandbox Code Playgroud)

我的服务器发送以下JSON:

 [{"id": "1233","name": "Karen","grade": "C"},{"id": "1234","name": "Susan", "grade": "F"}]
Run Code Online (Sandbox Code Playgroud)

当我点击按钮并在Chrome中查看控制台时,我看到:

首先点击:

[] - Corrected -just an empty array
Run Code Online (Sandbox Code Playgroud)

第二次点击:

[
Object
  grade: "C"
  id: "1233"
  name: "Karen"
  __proto__: Object
, 
Object
  grade: "F"
  id: "1234"
  name: "Susan"
  __proto__: Object
]
Run Code Online (Sandbox Code Playgroud)

第一个问题是为什么需要两次点击?第二:我如何简单地将等级(作为集合和id)分配/绑定到文本框 <li>或其他UI元素(当ajax弹出时更好地使其可观察).

Pau*_*aul 7

您看到的控制台消息来自click事件处理程序.来自render方法的控制台消息永远不会被调用.

您在第一条日志消息中看不到任何内容,因为它fetch是一种异步方法,所以当您toJSON在之后调用时fetch,尚未从fetch方法中填充该集合.

您需要对代码进行一些更改才能使其按预期工作.

首先,您需要在实例化视图时传入集合

//original
window.appview = new AppView();
//new
window.appview = new AppView({ collection: window.students });
Run Code Online (Sandbox Code Playgroud)

然后在视图中,您需要绑定到传递给构造函数的集合上的重置事件.(您必须绑定到实例化的对象,而不是像您最初那样的对象定义)

    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());
        }
    });
Run Code Online (Sandbox Code Playgroud)

现在,在您的点击事件中注释掉控制台日志消息,然后您只需单击一次,您将看到来自render方法的控制台日志消息.

 $('#test').click(function(){
     //var students = new Students();
        students.fetch();
        //var q = students.toJSON();
        //console.log(q);
    /*  
        students.create({
            name: 'John',
            grade: 'A'
        }); */
    })
Run Code Online (Sandbox Code Playgroud)

  • 写得很好的答案.如果有人想玩工作代码 - **[这里是](http://jsbin.com/awahog/2/edit#javascript,live)**. (3认同)