我的视图不接收数据从我的控制器

My view dont recieve data from my Controller

本文关键字:我的 控制器 数据 视图      更新时间:2023-09-26

我将只显示我有问题的那部分代码。如果您认为需要查看所有代码,请告诉我。

我的控制器:

index: function() {
    var documents = new App.Collections.Documents();
    documents.fetch({
        success: function() {
            new App.Views.Index({ collection: documents });
        },
        error: function() {
            new Error({ message: "Error loading documents." });
        }
    });
},

我的观点:

App.Views.Index = Backbone.View.extend({
    initialize: function() {
        console.log(this.documents);
        this.documents = this.options.documents;
        this.render();
    },
    render: function() {
        if(this.documents.length > 0) {
            var out = "<h3><a href='#new'>Create New</a></h3><ul>";
            _(this.documents).each(function(item) {
                out += "<li><a href='#documents/" + item.id + "'>" + item.escape('title') + "</a></li>";
            });
            out += "</ul>";
        } else {
            out = "<h3>No documents! <a href='#new'>Create one</a></h3>";
        }
        $(this.el).html(out);
        $('#app').html(this.el);
    }
});

文档代码的console.log为:undefined在控制器中,var document有效。

WHYYyY吗?如何在视图中访问控制器发送的json ?

谢谢,

console.log(this.documents);

this.documents = this.options.documents;

this.documents设置之前使用console.log

更新:

new App.Views.Index({ collection: documents });

this.documents = this.options.documents;

不应该是this.documents = this.options.collection;吗?因为我不认为你会放弃这个选择。

您通过collection: documents,因此在您的视图中您使用this.collection访问它。

查看显示它工作的jsfiddle: http://jsfiddle.net/dira/TZZnA/

我不太懂骨气…但是this.documents是在进入初始化函数之前定义的吗?似乎不是-试着切换行:

this.documents = this.options.documents; // define the variable
console.log(this.documents); // console log it