2013-03-02 53 views
0

我從主幹中的其餘網址獲取模型對象的集合。然後我遍歷集合,並使用下劃線模板幫助器方法來處理來自模型的數據。但是在調用屬性時我得到了未定義的defaultImg。backbone.js模型屬性undefined

查看:

define (['jquery','underscore','backbone'],function($,_,Backbone){ 
PopVideoView = Backbone.View.extend ({ 
    tagName:"li", 
    //template: _.template($('#popView').html()), 
    template: _.template("<li><img src='<%= defaultImg %>'/></li>"), 
    render: function() 
    { 
     console.log(this.model.toJSON()); 
     this.template(this.model.toJSON()); 
     this.$el.html(this.template); 
     return this; 
    } 
}); 
return PopVideoView; 
}); 

另一種觀點認爲:

define(['jquery','underscore','backbone','collections/PopVideos','views/PopVideo'],function($,_,Backbone){ 
PopVideosView = Backbone.View.extend ({ 
    el:"#pop", 
    render: function() 
    { 
     this.collection.each (function(video) 
     { 
      popVideoView = new PopVideoView({model:video}); 
      this.$el.append (popVideoView.render().el).hide().fadeIn(300); 
     },this); 
     return this; 
    }, 
}); 
return PopVideosView; 
}); 

這是我從Chrome開發者控制檯獲得:

Object {video_id: "1G4isv_Fylg", video_name: "Coldplay - Paradise ", defaultImg: "http://i.ytimg.com/vi/1G4isv_Fylg/mqdefault.jpg", genre: "pop", date: "Feb 16, 2013 1:01:33 PM"…} 
Uncaught ReferenceError: defaultImg is not defined 

什麼,我做錯了什麼?

這是模型&集合:

define (['jquery','underscore','backbone'],function($,_,Backbone){ 
Video = Backbone.Model.extend ({ 
    urlRoot:"/video", 
}); 
return Video; 
});//end define 

define(['backbone','models/Video'],function(Backbone,Video) { 
PopVideosCollection = Backbone.Collection.extend ({ 
    model:Video, 
    url:"/pop/3/1" 
}); 
return PopVideosCollection; 
}); 

回答

1

我發現這個問題,我只是需要做這樣的:

this.$el.html(this.template(this.model.toJSON())); 

代替:

this.template(this.model.toJSON()); 
this.$el.html(this.template); 
+0

對,如果你使用'html()'函數,它會調用該函數,但jQuery不會給你的模板函數所期望的參數。 – 2013-03-02 03:46:25

1

render方法您的PopVideoView有一些問題:

template: _.template("<li><img src='<%= defaultImg %>'/></li>"), 
render: function() 
{ 
    console.log(this.model.toJSON()); 
    this.template(this.model.toJSON()); 
    this.$el.html(this.template); 
    return this; 
} 

當你調用_.template,你會得到一個功能回到所以這個:

this.template(this.model.toJSON()); 

是有道理的,只是你把自己的HTML返回值。這一部分:

this.$el.html(this.template); 

是你走到哪裏錯了,你傳遞的功能,jQuery的html方法,並從fine manual

的.html(函數(指數,oldhtml))

函數(index,oldhtml)

返回要設置的HTML內容的函數。

因此,jQuery打電話給您的this.template函數使用它不理解的參數。然後編譯的模板函數在某處尋找defaultImg,沒有找到它,並且因爲沒有defaultImg而得到了ReferenceError

你不想給函數傳遞給html(),要評估模板功能,它的返回值交給html()

render: function() 
{ 
    this.$el.html(this.template(this.model.toJSON())); 
    return this; 
} 

而且順便說一句,你真的應該使用var時定義你的意見和模型:

define (['jquery','underscore','backbone'],function($,_,Backbone){ 
    var PopVideoView = Backbone.View.extend ({ 
    ^^^ 

這些變量是全球性的,如果你不var他們。

相關問題