0

我遇到的情况是我的 fetch 工作正常,我可以看到骨干集合中的数据,如果我进入将项目从集合中分配给模型 var 或暂停一两秒的方法,一切都很好:this.member 的代码行被填充

this.member = this.members.get(1);

. 如果我只是让代码运行,我最终会将一个空模型传递给我的视图。我不明白我错过了什么。访问集合之前是否需要绑定集合中的数据?我正试图爱上骨干,但到目前为止,她一直是个残忍的情妇……

`

//create the namespace
var Endeavor = {
    Models: {},
    Collections: {},
    Views: {},
    Templates: {}
};

Endeavor.Models.Member = Backbone.Model.extend({
    idAttribute: "Id"
});

Endeavor.Collections.Members = Backbone.Collection.extend({
    model: Endeavor.Models.Member,
    url: "Http://localhost:60000/api/members/" + "1", // $.cookie('UserId') 
    initialize: function () {
        console.log("Members collections init");
    }
});



Endeavor.Views.MemberView = Backbone.View.extend({
    id: "memberForm",
    template: "#memberTemplate",
    initialize: function () {
        console.log('init member view');
    },
    render: function () {
        console.log('memberView render called');
        console.log(this.model.toJSON());
        var html = $(this.template).tmpl();
        $(this.el).html(html);
        $("#Name").text = this.model.Name;
    }
});

jQuery(document).ready(function () {
    // router
    Endeavor.Router = Backbone.Router.extend({
        routes: {
            "": "lists",
        },

        lists: function () {
            this.members = new Endeavor.Collections.Members();
            this.members.fetch();

            this.member = this.members.get(1);

            var memberView = new Endeavor.Views.MemberView({ model: this.member });
            memberView.render();
            $("#content").html(memberView.el);
        }
    });
    // populate local variables
    var appRouter = new Endeavor.Router();
    Backbone.history.start();
});

`。

4

1 回答 1

2

Members.fetch是异步调用。尝试render查看members reset事件,或success在方法中传递回调fetch,或调用this.members.fetch({async: false}). 有许多不同的选择。

于 2012-10-09T15:32:31.733 回答