2014-11-01 73 views
0

我有一個Backbone應用程序。Backbone.js Uncaught ReferenceError下劃線模板

的json看起來像這樣,

{ 
    "cities": [ 
    "Kävlinge", 
    "Lund", 
    "Enskede", 
    "Vadstena" 
    ] 
} 

我的骨幹收集代碼

var Cities = Backbone.Collection.extend({ 
    url: 'configuration/city.json' 
}); 

var Index = Backbone.View.extend({ 
    initialize: function(){ 
    this.cities = new Cities(); 
    }, 
    el: '.page', 
    render: function(){ 
    var self = this; 
    this.cities.fetch({ 
     success: function(cities){ 
     console.log(cities.models[0].attributes.cities); 
     var template = _.template($('#city-dropdown').html(),{cities: cities.models[0].attributes}); 
     self.$el.html(template()); 
     } 
    }); 
    } 
}); 

var Router = Backbone.Router.extend({ 
    routes: { 
    '' : 'home' 
    } 
}); 
var router = new Router(); 

var index = new Index(); 
router.on('route:home',function(){ 
    index.render(); 
}); 

Backbone.history.start(); 

該聲明的console.log下劃線模板函數打印之前我必需的JSON陣列,但在我的腳本標籤,它只是Uncaught ReferenceError:城市沒有定義,

是我的Json不正確,或者是我的骨幹代碼不正確,我很困惑。似乎很傻。請協助。

<script type="text/template" id="city-dropdown"> 
     <select class="selectpicker"> 
     <%= _.each(cities, alert) %> 
     </select> 
    </script> 
+0

最近更改了'_.template'的行爲(請參見重複項),我懷疑您看到了操作中的更改。 – 2014-11-01 17:49:37

回答

1

由於下劃線1.7.0:

Underscore templates no longer accept an initial data object. _.template always returns a function now.

所以現在用於設置模板選項_.template函數的第二個可選的參數。將對象傳遞給complied函數:

var template = _.template($('#city-dropdown').html()); 
self.$el.html(template({ 
    cities: cities.models[0].attributes // cities.toJSON() 
})); 
+1

但是直到1.7.0(2014-08-26發佈),你可以說'_.template(template_source,data)'直接進入HTML而不需要中間步驟。很多教程和舊代碼還沒有趕上。 – 2014-11-01 17:51:29