骨架模型变量仅在我进入方法时填充

时间:2012-10-09 15:24:08

标签: backbone.js

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

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

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

`

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

`。

1 个答案:

答案 0 :(得分:2)

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