0

我有一个应用程序只在 $(document).ready 中加载一次数据。集合视图和模型视图之间存在链接。视图具有异步架构,因此它们在页面刷新时呈现。但是当我点击链接时,什么都没有呈现,因为数据已经被获取并且没有事件被触发。是否有允许处理这两种情况的插件或技巧?

Backbone.Collection.prototype.lazyLoad = function (id) {
    var model = this.get(id);
    if (model === undefined) {
        model = new this.model({ id: id });
        this.add(model);
        model.fetch();
    }
    return model;
}

var Col = Backbone.Collection.extend({
    model: Model,
});

var Model = Backbone.Model.extend({});

var ColView = Backbone.View.extend({
    ...
    initialize: function () {
        this.collection.on('reset', this.render);
    }
});

var ModelView = Backbone.View.extend({
    ...
    initialize: function () {
        this.model.on('change', this.render);
    }
});

var AppRouter = Backbone.Router.extend({
    routes: {
        "": "colView",
        "col/:id": "modelView"
    },

    colView: function () {
        new ColView(collection: col);
    }

    modelView: function (id) {
        new modelView(model: col.lazyLoad('modelId'));
    }
});

$(document).ready(function () {
    col = new Col;
    col.fetch();
    app = new AppRouter();
});
4

1 回答 1

1

据我了解,您希望它渲染并显示视图,但是因为col已经被获取,所以这不会触发change您绑定到ModelView's渲染事件的事件。好吧,您总是可以自己调用 ModelView 的渲染。

modelView: function (id) {
    var view =  new modelView({ model: col.lazyLoad('modelId') });
    view.render();
}
于 2012-06-20T14:08:33.550 回答