在集合中查找模型

3
我有一组模型,通过服务器调用添加到集合中。所有的模型都被添加并且在集合中追踪。现在我想要一种查找集合并根据模型内指定的id属性返回模型的方法。我不是在谈论内置的id集合,而是指集合中每个模型的自定义id。
目前我有这个代码,但我的_detect函数没有返回我想要的结果。
    var collection = Backbone.Collection.extend({


        initialize: function( ) {
            _.bindAll(this);
            this.bind('add', this.modelIsAddedd);
            this.serverCall();
        },

        modelIsAddedd: function(model){
            console.log('model = ', model);
        },

        getModelByCustomID: function( id ){

            var model = this.detect( id, function( model ){ return model });

        },

        serverCall: function(){

            $.ajax({
                my ajax call with success and error

            });
        },

        onSuccess: function(response){
            this.add(response.data);
        }

    });

});

这个自定义ID在系统中所有模型中都是唯一的吗?你能通过idAttribute将其设置为模型的id吗? - Crescent Fresh
是的,customID对于集合中的每个模型都是唯一的。 - Chapsterj
1个回答

3

好的,我已经搞清楚了,以防其他人需要答案。

getModelByCustomID: function( id ){

        var model = this.detect( function( model ){ 
            return model.get('customIDName') == id;
        });

},

6
你要寻找的内容可以直接使用:如果你将模型的idAttribute属性设置为"customIDName",那么不仅可以方便地通过myModel.id快捷获取myModel.get('customIDName'),还可以使用超快速的基于哈希的Collection.get(id)方法,因此你无需重新发明轮子。请注意保持原文意思不变。 - Crescent Fresh
我不知道你可以设置model.idAttribute = "customID"。 - Chapsterj
天才!刚刚浪费了好几个小时在这上面。本应该先看文档的! - simonmorley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接