Collection of objects of multiple models as the iterable content in a template in Ember.js

前端 未结 2 1178
萌比男神i
萌比男神i 2021-02-11 06:27

I am trying to build a blog application with Ember. I have models for different types of post - article, bookmark, photo. I want to display a stream of the content created by th

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-11 07:01

    It's a little complicated than that, but @twinturbo's example shows nicely how to aggregate separate models into a single array.

    Code showing the aggregate array proxy:

    App.AggregateArrayProxy = Ember.ArrayProxy.extend({
        init: function() {
            this.set('content', Ember.A());
            this.set('map', Ember.Map.create());
        },
    
        destroy: function() {
            this.get('map').forEach(function(array, proxy) {
                proxy.destroy();
            });
    
            this.super.apply(this, arguments);
        },
    
        add: function(array) {
            var aggregate = this;
    
            var proxy = Ember.ArrayProxy.create({
                content: array,
                contentArrayDidChange: function(array, idx, removedCount, addedCount) { 
                    var addedObjects = array.slice(idx, idx + addedCount);
    
                    addedObjects.forEach(function(item) {
                        aggregate.pushObject(item);
                    });
                },
                contentArrayWillChange: function(array, idx, removedCount, addedCount) { 
                    var removedObjects = array.slice(idx, idx + removedCount);
    
                    removedObjects.forEach(function(item) {
                        aggregate.removeObject(item);
                    });
                }
            });
    
            this.get('map').set(array, proxy);
        },
    
        remove: function(array) {
            var aggregate = this;
    
            array.forEach(function(item) {
                aggregate.removeObject(item);
            });
    
            this.get('map').remove(array);
        }
    });
    

提交回复
热议问题