我正在嘗試製作一個小的backbone.js應用程序,但與事物的順序發生衝突。backbone.js視圖在模型提取之前呈現
在我的html文件,我在包頭中的兩個腳本塊:
<script type="text/template" id="model-template">
<a href="#"><%= title %></a>
</script>
<script type="text/javascript">
jQuery(function(){
window.model.fetch();
});
</script>
在我app.js,我已經定義了一個簡單的模型,視圖和路由器。
(function($) {
window.MyModel = Backbone.Model.extend({
url: '/mymodel'
});
window.mymodel = new MyModel();
$(document).ready(function() {
window.MyModelView = Backbone.View.extend({
template: _.template($('#mymodel-template').html()),
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
});
window.MyApp = Backbone.Router.extend({
routes: {
'': 'home'
},
initialize: function() {
this.myModelView = new MyModelView({
model: window.mymodel
});
},
home: function() {
var $body = $('body');
$body.empty();
$body.append(this.myModelView.render().el);
}
});
$(function() {
window.App = new MyApp();
Backbone.history.start({pushState: true});
});
})(jQuery);
該應用程序由一個簡單的sinatra應用程序提供服務。該URL /mymodel
供應靜態JSON文件:
{
"title": "My Model",
}
當加載應用程序,我得到在JavaScript控制檯中的錯誤:
Uncaught ReferenceError: title is not defined
這個問題似乎是,該視圖前呈現自己該模型從服務器獲取。這是爲什麼?
昨天,我跟蹤了PeepCode的前兩個backbone.js截屏視頻。我試圖將我的應用程序與屏幕錄像中的應用程序進行比較,但無法看到爲什麼我的應用程序想要工作的原因。
有什麼建議嗎?
花了我幾個小時......小時才發現,這就是爲什麼我的應用程序不工作,工作了一些時間而不是其他工作,或者在某些瀏覽器而不是其他工作。當我想到如何獲取應該工作的一種菜鳥錯誤。學過的知識。 我覺得太多的骨幹例子使用硬編碼的數據和非常重要的概念,就像今年秋天一樣。 – IcedDante 2014-11-29 06:14:45