2016-08-05 90 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

你有什么更好的主意吗? –