BackboneJS嵌套视图无法呈现

时间:2016-02-04 08:03:36

标签: backbone.js

我在lightbox中有form html <select>作为子视图。 对于我从服务器加载的select <option>数据,我有select

的单独模型和集合
<select name="organization" id="organization" class="main__form--select main__form--select--js">
    <option value="no">Organizations not found, Please add one</option>
</select>

选项模型(optionModel)

return Backbone.Model.extend({
    defaults : {
        "name" : 'KFC',
        "email" : 'info@kfc.com',
        "image" : '/kfc.jpg',
        "descrption" : 'Lorem Ipsum'
    }
});

这是模型的视图

return Backbone.View.extend({    
    model : optionModel,
    template : _.template(template),
    render : function () {
        this.$el.html(this.template(this.model.attributes));     
        return this;
    }
});

这是选项集

return Backbone.Collection.extend({
    model : optionModel,
    getQuery : function(){
        //all my query codes
    }
});

选项集合视图render()代码

this.collection.each(function (optionModel) {
    // inserting each options view to an array
    _this._optionsViewArray.push(
        new OptionView({
            model: optionModel
        }).render().el
    );
});
//inserting array to collection view container
_this.$el.html(_this._optionsViewArray);
return this;

我的父视图(表单视图)我在使用下划线_.wrap和在该函数内部的渲染函数之后创建

//<select>
var _selector = this.$el.find('#organization');

optionsView = new OptionsCollectionView({
    collection : optionsCollection,
    $el: _selector
});
optionsCollection.getQuery();
optionsView.render();

但是Form完全加载并且选项集合成功查询,但<select> html没有任何变化,它没有更新。

2 个答案:

答案 0 :(得分:0)

假设getQuery()执行异步查询(使用jQuery或Collection.fetch()),问题(或至少一个问题)是您即将调用optionsView.render() ,在返回查询结果之前。

你可以输入任意5秒的超时来验证这是这样的问题:setTimeout(function() { optionsView.render(); }, 5 * 1000);,但正确的方法是从jQuery done处理函数调用render( $.ajax({done: function() { ... }}))或(更好)一个Backbone sync事件处理程序(只有在通过Backbone集合fetch()执行查询时才会调用此事件):optionsCollection.on('sync', function() { ... });

答案 1 :(得分:0)

你的例子不完整。但是,鉴于在Backbone和jQuery中提取通常是异步的,这是最明显的问题,optionsCollection将在optionsView = new OptionsCollectionView({ collection : optionsCollection, $el: _selector }); optionsView.listenTo(optionsCollection, 'update', optionsView.render); optionsCollection.getQuery(); 有机会完全加载集合之前运行。您可以通过收听集合更新事件来解决此问题:

sync

您可以收听update事件,但是收听render: function() { var $el = this.$el; $el.empty(); this.collection.each(function (optionModel) { var view = new OptionView({ model: optionModel }); $el.append(view.render().$el); }); return this; } 表示对集合的本地更改也会触发更新您的观看。

渲染函数也存在问题,因为您将一个html元素数组传递给jQuery html函数。

{{1}}

但是,您可能最好使用标准集合视图模式,或者像Backbone.CollectionView - http://rotundasoftware.github.io/backbone.collectionView/

相关问题