Skip to content

'this' inside View.render() being set to the model? #2

Closed
@bgrins

Description

I must be doing something wrong here. I'm trying to make a little demo to see what I can do with backbone, and basing it off your sample code. I an get "Uncaught TypeError: Cannot call method 'toJSON' of undefined". I see why it is doing this, because the bind("change", taskView.render) call is setting the context to the model (which the alert confirms), but it seems like there should at least be an argument to the render function to get access to the view. Maybe I am just going about it the wrong way? (see the sample code below).

Thanks,
Brian

<script type='text/javascript'>
var Task = Backbone.Model.extend({
    text: '',
    isFinished: false
});

var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'task',
    render: function(model) {
        alert("does 'this' == model? " + (this == model));
        // Can't call render, because 'this' is not referencing the view
        $(this.el).html(this.template.render(this.model.toJSON()));
        return this;
    }
});


$(init);
function init() {

    var tasks = new Backbone.Collection;
    tasks.bind("add", function(task) {
        var taskView = new TaskView({
            model: task,
            id: 'task-' + task.cid
        });
        task.bind('change', taskView.render);
    });
    
    tasks.add([
      new Task({text: "Task 1"}),
      new Task({text: "Task 2"})
    ]);
    
    tasks.each(function(task) {
        task.set({ isFinished: false });
    });
}
</script>

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions