mergul
mergul

Reputation: 19

Uncaught TypeError: Object [object Window] has no method 'each' function

Hey guys here is my js file and I am taking error message about each function at line:24 and I do not know why I couldnt find whats wrong. I am just trying to see the list of items on the console.log panel but it does not even give me list on the html page.

(function() {

    window.App = {

        Models: {},
        Collections: {},
        Views: {}
    };

    window.template = function(id){
        return _.template( $('#' + id).html() );
    };

App.Models.Task = Backbone.Model.extend({});

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

App.Views.Tasks = Backbone.View.extend({
    tagName: 'ul',

    render: function(){
        this.collection.each( this.addOne, this);

        return this;
    },

    addOne: function(task){
        //creating new child view
        var taskView = new App.Views.Task({ model: task });

        //append to the root element
        this.$el.append(taskView.render().el);
    }
});

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

    template: template('taskTemplate'),

    events: {
        'click .edit': 'editTask'
    },

    editTask: function(){
        alert('you are editing the tas.');
    },

    render: function(){
        var template = this.template( this.model.toJSON() );
        this.$el.html(template);
        return this;
    }

});


var tasksCollection = new App.Views.Task([
{
    title: 'Go to the store',
    priority: 4
},
{
    title: 'Go to the mall',
    priority: 3
},
{
    title: 'get to work',
    priority: 5
}
]);

var tasksView = new App.Views.Tasks({ collection: tasksCollection });

$('.tasks').html(tasksView.render().el);

})();

Upvotes: 1

Views: 623

Answers (2)

STEEL
STEEL

Reputation: 10007

Hi this is happening cus your each method not able to find the collection. As well the singular Task to Tasks

At this line: Change this

var tasksCollection = new App.Views.Task([

TO, this:

var tasksCollection = new App.Collections.Tasks([

Upvotes: 0

mu is too short
mu is too short

Reputation: 434596

You're creating a view instance as though it was a class:

App.Views.Tasks = Backbone.View.extend({ /* ... */ });

var tasksCollection = new App.Views.Task([
{
    title: 'Go to the store',
    priority: 4
},
//...

and then you create another instance of that view and hand it tasksCollection as though it really was a collection:

var tasksView = new App.Views.Tasks({ collection: tasksCollection });

But views and collections are different things and only collection's have an each method (unless you add an each to your view of course).

You want to create tasksCollection as an App.Collections.Task:

var tasksCollection = new App.Collections.Task([
{
    title: 'Go to the store',
    priority: 4
},
//...

Upvotes: 1

Related Questions