2013-04-27 81 views
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' 
     }) 
    } 
}); 

如何我添加類名ŧ o這li元素中的每一個?這裏有什麼錯,任何人都可以幫我排序,或者可以給我一個正確的方法來過濾一個集合並將類名應用到它的元素中?

Here is the jsfiddle.

+0

烏盧格別克Komilovich - 你爲什麼刪除jsfiddle? – 3gwebtrain 2013-04-27 13:59:42

+0

您在調用showMe函數之前/之前沒有調用渲染 – 2013-04-27 14:08:34

+0

我很抱歉無法正確更改,我確實在更改您的時間進行更改 – 2013-04-27 14:10:42

回答

2

首先,與骨幹網和下劃線,你通常不希望呼籲集合下劃線的方法,例如:

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

你,而不是要撥打的骨幹收集等效方法( http://documentcloud.github.io/backbone/#Collection-Underscore-Methods):

this.collection.filter(function(item){ 

第二你拼錯的 「分數」 作爲 「socre」;不要試圖成爲一個混蛋,只是指出它,因爲這樣的拼寫錯誤很容易導致錯誤。

第三,意見期望a模型爲他們的模型參數,但您的getHighSocre方法返回過濾器的結果,即。一個陣列的車型,所以這行:

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

是行不通的。如果您只想要第一個得分高於60分的模型,請嘗試使用find而不是filter,如果您確實希望您的視圖使每個模型的得分高於60,那麼您可能需要將這些模型轉換爲新集合並將其作爲視圖的集合(而不是其模型)傳遞。

P.S.

這不是答案的真正組成部分,而只是一個註釋;如果你不熟悉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");