Oleg
Oleg

Reputation: 2821

listen to model events in view

I try to render view when model changes. Could you please tell why this code doens't wok?

var TodoView = Backbone.View.extend({
    initialize: function() {
        this.model.on('change', this.render, this);
    },
});

It gives error:

TypeError: this.model.on is not a function

But it looks like this code works:

var TodoView = Backbone.View.extend({
    initialize: function() {
            _.bindAll(this, 'render');  
        this.model.bind('change', this.render);  
    },
});

These libraries are used:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>   

Upvotes: 1

Views: 2321

Answers (1)

jevakallio
jevakallio

Reputation: 35890

The on and off methods were added to Backbone in version 0.9.0, and it looks like you are still version 0.3.3. You can continue to use bind and unbind. The new on/off methods are just aliases for the same thing.

Alternatively you should consider updating your Backbone version. Since 0.3.3 there have been hundreds of other improvements and bugfixes to Backbone, so you should update to the newest (0.9.10) if you're able. At the same time you need to update underscore to version >= 1.4.3

Upvotes: 4

Related Questions