2013-11-26 34 views
0

我試圖實現通過使用模型的屬性作爲視圖中的變量來呈現HTML塊。Backbone.js視圖屬性中的變量

App = Backbone.Model.extend({ 
     contentType: "text" 
     }); 

AppView = Backbone.View.extend({ 
     ContentTpl: _.template($('#slide-'+this.model.get('contentType')).html()), 

     render: function(){ 
      $('#wrapper').html(this.ContentTpl());  
     } 
     }); 

var app = new App(); 
var appView = new AppView({model: app}); 
appView.render(); 

HTML:

<div id="wrapper"> 
</div> 

<script type="text/template" id="slide-text"> 
    <p>This is a test</p> 
</scrip> 

但是,這會導致錯誤......

+0

你得到了什麼錯誤? –

+0

未捕獲TypeError:無法調用未定義的方法「get」 – FLuttenb

回答

2

你定義你的看法是錯誤的。

你有

AppView = Backbone.Model.extend({ 

應該

AppView = Backbone.View.extend({ 

,並不能求this.model視圖初始化之前,請不要使用以下:

ContentTpl: function() { 
    return _.template($('#slide-'+ this.model.contentType).html()); 
}, 

和, contentType不是模型屬性,它是模型對象上的屬性,不能使用get()。

將其定義爲一個模型屬性,你必須要麼把它定義爲模型的默認值,或者通過它,當你實例化一個對象:

var app = new App({contentType: 'text'}); 

App = Backbone.Model.extend({ 
    defaults: { 
    "contentType": "text" 
    } 
}); 
+0

sry,我忘了在我的帖子中。但當然,我在我的代碼中有'this.ContentTpl()'。我編輯了我的第一篇文章 – FLuttenb

+0

剛編輯我的答案。 –

+0

另一個錯誤.. sry ..剛剛編輯我的帖子 – FLuttenb

1

你必須在initialize函數中加載您的模板。 this.model在那時不存在。

initialize: function() { 
    this.ContentTpl = _.template($('#slide-'+this.model.get('contentType')).html()); 
} 

但是,這仍然是一個糟糕的模式形式的骨幹。我會注入它作爲一個選項。

var template = $('#slide-'+this.model.get('contentType')).html(); 
var appView = new AppView({model: app, ContentTpl: template }); 
... 

// in your view 
initialize: function(options) { 
    this.ContentTpl = _.template(options.ContentTpl); 
} 
+0

@ FLuttenb它不會是全局的,但它將是一個實例屬性。你可以用'this.ContentTpl'通過'render'來獲得它。 –

+0

這是一個壞主意,因爲我有很多這些模板,我想盡可能多地在我的骨幹模型中保留代碼。 – FLuttenb

+0

@ FLuttenb模型對於存儲模板並不是很理想。 –