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

How do I view model data after fetch in backbone.js

本文关键字:何查看 模型 数据 获取 backbone js      更新时间:2023-09-26

我对来自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'
        }); */
    })
});

我的服务器发送以下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弹出时使其可见)。

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

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

为了使代码按预期工作,您需要对代码进行一些更改。

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

//original
window.appview = new AppView();
//new
window.appview = new AppView({ collection: window.students });

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

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

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

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