0

在我的主干视图中,我正在从我的收藏中获取模型..

initialize:function(){
    this.collection = new collection(student);
    this.render();
},

从这个集合中,我使用过滤器方法过滤高价值模型:(点击我触发)

getHighSocre:function(){
    return _.filter(this.collection.models, function(item){
         return parseInt(item.get('scored')) > 60
    })
},
showHighScore:function(){
    var hView = new studentView({model:this.getHighSocre()}); // sending to single view
    hView.showMe(); // I am calling this method to add a class name to each 'li' element..
}

这是我的单一观点:

var studentView = Backbone.View.extend({
    tagName:'li',
    events:{
        'click':"called"
    },
    template:_.template($("#studentTemplate").html()),
    render:function(){
        this.$el.append(this.template(this.model.toJSON()));
        return this;
    },
    called:function(){
        if(this.model.get('scored') > 60){
            this.$el.css({
                background:"#EFEFEF"
            })
        }else{
            this.$el.css({
                background:"#FCBABA"
            })
        }

    },

    showMe:function(){ // I am passing here to add a class name

        console.log(this) // make the array... here

        this.$el.css({ // but this is not getting the dom element...
             border:'1px solid red'
         })
     }
});

如何将类名添加到每个li元素?这里有什么问题,任何人都可以帮助我进行排序,或者可以给我一个正确的方法来过滤集合并将类名应用于它的元素?

这是jsfiddle。

4

1 回答 1

2

首先,使用 Backbone 和 Underscore,您通常不想在 Collections 上调用 Underscore 方法,例如:

_.filter(this.collection.models, function(item){

相反,您想调用 Backbone Collection 等效方法 ( http://documentcloud.github.io/backbone/#Collection-Underscore-Methods ):

this.collection.filter(function(item){

其次,您将“score”拼写为“socre”;不要试图成为一个混蛋,只是指出它,因为这样的拼写错误很容易导致错误。

第三,视图期望模型参数的模型,但您的方法getHighSocre返回过滤器的结果,即。一模型,所以这一行:

new studentView({model:this.getHighSocre()});

行不通。如果您只想要第一个得分高于 60 的模型,请尝试使用find代替filter作为视图的集合(而不是作为它的模型)。

附言

这实际上不是答案的一部分,而只是一个注释;如果您不熟悉 Javascript 的三元运算符,您可能需要检查一下,因为它可以让您减少所有这些:

    if(this.model.get('scored') > 60){
        this.$el.css({
            background:"#EFEFEF"
        })
    }else{
        this.$el.css({
            background:"#FCBABA"
        })
    }

只是:

var isAbove60 = this.model.get('scored') > 60;
this.$el.css('backgroundColor', isAbove60 ? "#EFEFEF" : "#FCBABA");
于 2013-04-27T20:29:05.133 回答