2016-08-05 93 views
-1

我有這下面的代碼,我是昨天 但今天的工作,當我重新運行該代碼中,我得到以下錯誤: 未捕獲的ReferenceError:未定義tasksCollection未捕獲的ReferenceError在骨幹JS

(function(){ 
window.App={ 
    Models:{}, 
    Collections:{}, 
    Views:{} 
    }; 
window.template=function(id){ 
    return _.template($('#' +id).html()); 
}; 
App.Models.Task=Backbone.Model.extend({}); 

App.Collections.Tasks=Backbone.Collection.extend({ 
    model:App.Models.Task 
    }); 

App.Views.Task=Backbone.View.extend({ 
    tagName:'li', 

    template:template('taskTemplate'), 

    initialize:function(){ 
     //when model change it will change ! 
     //this.model.on('change',this.render,this); 
     this.render(); 
     }, 

    events:{ 
     'click .edit':'editTask', 
     'click .delete':'deleteTask' 
    }, 
    editTask:function(){ 
     var newTitle = prompt('what would you like to be your title?',this.model.get('title')); 
     this.model.set('title',newTitle); 
    }, 
    deleteTask:function(){ 
     alert('delete');  
    }, 
    render:function(){ 
     var template= this.template(this.model.toJSON()); 
     this.$el.html(template); 
     return this; 
    } 
}); 
App.Views.Tasks=Backbone.View.extend({ 
    tagName:'ul', 
    initialize:function(){ 
     this.render(); 
    }, 
    render:function(){ 
     this.collection.each(this.addOne,this); 
     return this; 
    }, 
    addOne:function(task){ 
     //creat new child view 

     var taskView= new App.Views.Task({ model:task}); 
     taskView.render(); 

     //append to the root element 

     this.$el.append(taskView.render().el); 
    } 
}); 
var tasksCollection=new App.Collections.Tasks([ 
    { 
     title:'Hi', 
     name:'samin' 
    }, 
    { 
     title:'Hi', 
     name:'nazanin' 
    }, 
    { 
     title:'Baby', 
     name:'nazanin' 
    } 
]); 
var tasksView=new App.Views.Tasks({collection:tasksCollection}); 
console.log(tasksView.el); 
$('.tasks').html(tasksView.el); 
})(); 

我無法修復該錯誤。它看起來像一切應該運作良好 你們能幫我解決嗎?

+1

能否請您發表您的標記(taskTemplate和HTML)呢? – lucasjackson

+2

請發佈您的錯誤的堆棧跟蹤。 – Louis

回答

-1

一些研究,我搞清楚這樣

後,我們應該代替VAR來定義新的集合使用窗口。

怎麼樣? 這樣 - >

window.tasksCollection=new App.Collections.Tasks([ 
{ 
    title:'Hi', 
    name:'samin' 
}, 
{ 
    title:'Hi', 
    name:'nazanin' 
}, 
{ 
    title:'Baby', 
    name:'nazanin' 
} 
]); 
+1

儘可能避免將變量泄漏到全局空間中。在這裏介紹的情況下,我認爲沒有什麼好的理由可以泄露到全球空間。 – Louis

+0

你有什麼更好的主意嗎? –