2

看起来这应该是显而易见的,但是那里似乎有很多不同的例子,其中大部分都会对我造成错误,让我觉得它们已经过时了。基本情况是我有一个MessageModel链接到一个扩展ItemView的MessageView,MessageCollection链接到一个MessageCollectionView(itemView:MessageView)。我有一个稍微不寻常的场景,因为 MessageCollection 是异步填充的,所以当页面第一次呈现时,它是空的,并且会显示一个“正在加载”图标。也许我的结构不正确(见这里对于历史),但现在,我已经封装了向服务器发出初始请求并在 MessageCollection 对象中接收初始消息列表的代码,以便它自行更新。但是,鉴于此,我不清楚如何触发显示视图。显然,模型不应该告诉视图渲染,但是我尝试实例化视图并让它监听 modelChange 事件并调用“渲染”都没有奏效。

我努力了:

  1. 没有加载元素,只显示没有加载元素的CollectionView,但是在底层Collection刷新后它不会刷新。
  2. 将 modelEvents { 'change': 'render' } 添加到视图 --> Uncaught TypeError: Object function () { return parent.apply(this, arguments); 没有方法'on'
  3. 我也尝试过 this.bindTo(this.collection..) 但“this”并没有使用 bindTo 方法
  4. 最后,我尝试了,在 view.initialize: _.bindAll(this); this.model.on('change': this.render); --> Uncaught TypeError: Object function () { [native code] } has no method 'on'

这是代码

    Entities.MessageCollection = Backbone.Collection.extend({
        defaults: {
            questionId: null
        },
        model: Entities.Message,
        initialize: function (models, options) {
            options || (options = {});
            if (options.title) {
                this.title = options.title;
            }
            if (options.id) {
                this.questionId = options.id;
            }
        },
        subscribe: function () {
            var self = this; //needed for proper scope
            QaApp.Lightstreamer.Do('subscribeUpdate', {
                adapterName: 'QaAdapter',
                parameterValue: this.questionId,
                otherStuff: 'otherstuff',
                onUpdate: function (data, options) {
                    console.log("calling sync");
                    var obj = JSON.parse(data.jsonString);
                    self.set(obj.Messages, options);
                    self.trigger('sync', self, obj.Messages, options);
                }
            });
        },
    });

    Views.MessageCollectionView = Backbone.Marionette.CollectionView.extend({
        itemView: Views.MessageView,
        tagName: 'ul',
//        modelEvents: {
//            'change': 'render'
//        },
        onAfterItemAdded: function (itemView) {
            this.$el.append(itemView.el);
        }
    });

var Api = {
        subscribe: function (id) {
            var question = new QaApp.Entities.Question(null, { id: id });
            question.subscribe();
            var questionView = new QaApp.Views.QuestionView(question);
            QaApp.page.show(questionView);
        }
    };

我非常感谢我已经收到的所有帮助,并提前感谢您的关注。

4

1 回答 1

3

尝试这个:

var questionView = new QaApp.Views.QuestionView({
    collection: question
});
于 2013-09-06T17:47:00.973 回答