我環顧了各種教程和文檔,並且我仍然在使主幹路由器工作時遇到了一些麻煩。我正在OS X上的Sites文件夾中運行代碼(URL爲http://localhost/~plebrun
)。 http://localhost/~plebrun/#foo
和http://localhost/~plebrun/#type/books
都不起作用。思考?讓骨幹路由正常工作
(注:data_中*變量包含JSON數據)
/****************************/
/********** MODELS **********/
/****************************/
var Category = Backbone.Model.extend();
var Phrase = Backbone.Model.extend();
/****************************/
/******** COLLECTIONS *******/
/****************************/
var Type = Backbone.Collection.extend({
model: Category
});
/****************************/
/********** VIEWS ***********/
/****************************/
var TypeView = Backbone.View.extend({ /* a Type is a list of Categories */
el: $('#categories'),
initialize: function() {
_.bindAll(this, 'render');
this.render();
},
render: function() {
var ul_list = "";
_(this.collection.models).each(function(category) {
ul_list += '<li><a href="/category/' + category.get('id') + '"><h1>' + category.get('en') + '</h1><p>' + category.get('es') + '</p></a></li>';
});
$(this.el).append(ul_list);
}
});
/****************************/
/********* ROUTER ***********/
/****************************/
var AppRouter = Backbone.Router.extend({
routes: {
"/type/:src": "showType",
"/foo": "foo"
},
locate_data: {
"books": data_books,
"conversations": data_conversations,
"phrases": data_phrases
},
initialize: function() {
_.bindAll(this, 'showType');
},
foo: function() {
alert("foo")
},
showType: function(src) {
console.log(src);
var types = new Type(this.locate_data[src]);
new TypeView({ collection: types });
}
});
/****************************/
/********** INIT ************/
/****************************/
var foo = new AppRouter();
Backbone.history.start({pushState: true, root: "/~plebrun/"});
我也真的建議尋找一個模板引擎爲您的HTML渲染,骨幹自帶的下劃線模板功能應該足夠好。您可以擺脫TypeView.render中的臭味代碼, – OlliM 2012-03-13 15:42:46
好建議,最後我會使用Handlebars.js - 我只是想先弄清楚一些事情。不幸的是,刪除開始的正斜槓並沒有解決問題。 – Pierre 2012-03-13 16:19:04
我不確定這裏出了什麼問題。我建議在不使用pushState的情況下測試(不確定服務器是否重定向/ plebrun/foo到同一頁面)並在服務器的根目錄下運行,因此沒有歷史根參數。 – OlliM 2012-03-14 08:30:01