主干监听嵌套模型/集合

Backbone listen to nested models/collections?

本文关键字:集合 模型 嵌套 监听      更新时间:2023-09-26

下面是我所做的一个粗略的想法,集合是嵌套的,当this.collection.get('players')改变时,我需要调用getMax()

module.exports = LeadersCollectionView = Marionette.CompositeView.extend({
    className: 'live-stats',
    template: require('../../../templates/leaders/live-stats.hbs'),
    initialize: function() {
        this.listenTo(this.collection, 'change', this.render);
        //this.listenTo(this.collection.get('players'), 'change', this.render);
    },
    getMax : function(attribute) {
        console.log('getMax called')
        var home = this.collection.get('5368dcc1227a937829b2cb4a').players.models;
        var away = this.collection.get('5368dcd9227a937829b2cb4c').players.models;
        leaders = new PlayersCollection(home.concat(away))
        return leaders.max(function(leader) {
            return leader.get(attribute);
        });
    },
    templateHelpers:function(){
        return {
            maxPoints: this.getMax('points').get('player_name')
        }
    },
    itemView: leadersView,
    appendHtml: function(collectionView, itemView){
        collectionView.$('.live-data .created-teams').append(itemView.el);
    }
});

我使用的是主干关系,然后决定放弃它,现在我想我可能会再次需要它,但希望有一个更简单的方法。

所以,虽然可能有一个更好的方法来写getMax()函数(显然是静态的球队传入到现在),我不能真正使用它,如果我不能更新getMax()时,点在球员模型内的变化。

所以我的问题是,我可以在没有主干关系的情况下监听嵌套模型上的变化吗?我该怎么做?

看一下Backbone。DeepModel:你可以订阅改变:玩家。*活动

我只是想为任何需要的人提供一个自制的解决方案。实际上,您只需在模型声明中创建一个新方法,该方法通常允许您在触发属性时更新属性,以便您可以使用model.on("change:my.nested.attr");

// Create your model; inside create a new method that will
// set nested attributes (ie: setNestedAttr())
var nestedBackboneAttributeSample = Backbone.Model.extend({
    defaults: {
        id: null,
        nestedProperties: {
            name: null,
            age: null,
            email: null
        }
    },
    /**
     * [setNestedAttr Set nested attribute and fire change event]
     * @param {[type]} nestedObj [object inside of this.attributes]
     * @param {[type]} property  [property inside of nestedObj]
     * @param {[type]} value     [value to replace nestedObj[property] with]
     */
    setNestedAttr: function(nestedObj, property, value) {
        // get current nested obj from this.attributes
        var ref = this.get(nestedObj)
            triggerString = "change:" + nestedObj + "." + property;
        console.log("Nested Object retrieved =>");
        console.log(ref);
        // if this.attributes.nestedObj has the property and
        // value is defined
        if (ref.hasOwnProperty(property) && value != undefined) {
            ref[property] = value;
            this.set({ nestedObj: ref });
            // manually trigger.. backbone doesn't monitor nested attrs
            this.trigger(triggerString);
        }
    }
});
// now, let's run some sampel code to give you 
// an idea of how to use this.
var x = new nestedBackboneAttributeSample();
// setup event handler for on change w/specific nested attr
x.on("change:nestedProperties.name", function() {
    console.log("this event was fired!");
});
x.setNestedAttr("nestedProperties", "name", "Github")
// output => "this event was fired!"

我不能得到deepmodel或nestedmodels的工作,但这似乎是一个伟大的解决方案,它是如此简单,但我没有想到这样使用它。

this.collection.each(function(team) {
    team.players.bind('change', this.render);
}, this);