Backbone Model获取刷新事件未触发

Ami*_*haq 2 javascript backbone.js

我希望我可以抽象出所有相关部分.我的问题是当我从服务器获取模型时渲染方法没有执行的原因.

模型

var Document = Backbone.Model.extend({
    urlRoot: "/dms/reconcile/GetDocumentByDocumentId/"
});
Run Code Online (Sandbox Code Playgroud)

视图

window.DocumentView = Backbone.View.extend({
    el: $("#reconcile_document"),
    initialize: function () {
        this.model.bind('refresh', this.render) //also tried reset
    },
    render: function () {

        alert("Do awesome stuff here");

        return this;
    }
});
Run Code Online (Sandbox Code Playgroud)

路线

        var AppRouter = Backbone.Router.extend({
            routes: {
                "package/:id": "getPackage"
            },
            getPackage: function (packageid, p) {

                window._document = new Document({ id:packageid) });
                window.document = new DocumentView({ model: _document });

                _document.fetch();
            }
        });

        // Instantiate the router
        var app_router = new AppRouter;
Run Code Online (Sandbox Code Playgroud)

因此,当我去的时候,localhost:3000/#/Package/123我可以看到xhr调用localhost:3000/dms/reconcile/GetDocumentByDocumentId/123并且数据成功返回,但render函数永远不会执行.任何帮助将不胜感激.

干杯.

Der*_*ley 8

调用fetch()模型不会触发refresh事件.它将在获取数据后change通过调用触发事件set:

http://documentcloud.github.com/backbone/docs/backbone.html#section-40

http://documentcloud.github.com/backbone/#Model-fetch

更改您的事件处理程序,它应该工作:

window.DocumentView = Backbone.View.extend({
    el: $("#reconcile_document"),
    initialize: function () {
        this.model.bind('change', this.render, this);
    },
    render: function () {

        alert("Do awesome stuff here");

        return this;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 或者,您可以调用_document.fetch({success:_document.success_handler}).在success_handler中,您可以在模型上触发自定义事件. (3认同)