2013-11-28 238 views
0

http://jsfiddle.net/3pSg7/Uncaught ReferenceError:text is not defined

我不知道在這種情況下是否有人能夠幫助找到問題。 第6行顯示「Uncaught ReferenceError:text is not defined」。 使用模板和本地.txt文件進行測試,直到有API可用。

Backbone.js的模型腳本:

var Letter = Backbone.Model.extend({ 
urlRoot: 'data/json/news', 
initialize: function() { 
}, 
defaults: { 
    _type: "", 
    text: "",  
    is_read: 0 
} 
}); 

var News = Backbone.Collection.extend({ 
    model: Letter, 
    url: 'data/json/list_news.txt', 
    initialize: function() { 
    }, 
    fetchMyNews: function() { 
     this.fetch({async:false}); 
    } 
}); 

var news = new News(); 

查看腳本:

var NewsView = Backbone.View.extend({ 
initialize: function() { 
    this.isShown = false; 
    this.render(); 
    this.listenTo(news, "all", this.doListen); 
}, 

doListen: function(eventName){ 
    if(eventName == "change"){ 
     this.render(); 
    } 
}, 

isShown: false, 

events: { 
}, 

render: function() { 
    this.$el.attr("z-index", "1000"); 

    news.fetchMyNews(); 
    var sHtml = JST["news/row"](news.attributes); 
    $("#news_tbody").html(sHtml); 
} 
}); 
+1

你的小提琴並沒有真正做任何事情。您能否向我們提供您正在檢索的文本文件的示例內容? –

+0

您是否嘗試不使用'.txt'和文件名爲'list_news' –

回答

0

代碼中的幾件事情。

您正在爲您的收藏定義一個全局變量'news'。這不是建議,你可以通過一個新的集合,以你的觀點,當你實例化它:

var NewsView = new NewsView({ 
    collection: new News() 
}); 

,並更改視圖中所有的「新聞」參考「this.collection」

和我通常不喜歡異步ajax調用。嘗試將它們更改爲回調,或只是在視圖中聽取事件。哦,還有,儘量不要在render()中獲取數據。你的函數只能做他們命名的東西。 :)

所以在你看來:

initialize: function() { 
    this.isShown = false; 
    this.listenTo(this.collection, "all", this.doListen); 
    this.collection.fetch(); 
}, 

doListen: function(eventName){ 
    if(eventName == "change" || eventName == 'reset'){ 
    this.render(); 
    } 
} 

和渲染:

var sHtml = JST["news/row"](new.attributes); 
$("#news_tbody").html(sHtml); 

您呼叫news.attributes,慶幸的是在這裏集合。 「屬性」 沒有按」什麼都不給你。我不確定你的模板是什麼樣的,但是你可能會在你的模板中調用'.text',因爲news.attributes是未定義的,所以在這裏給出了這個錯誤。

相關問題