Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13422

Backbone return the last model that was changed?

I would like to create a view that renders a list of all the changes that happens to a model in the collection.

For instance on the main view that updates a model's "points" with a click, the model is updated the view is rendered, I want to have a view that listens to that occurrence and renders the information elsewhere.

Here is an example, I have three models kevin, mike, luke and the user clicks to add points to kevin the view captures that and renders content like... luke has scored 1 point.

I would create a feedView like below

var FeedView = Backbone.View.extend({

    el: '.live-feed',

    template: _.template($('#feedTemplate').html()),

    initialize: function() {
        this.listenTo(this.collection, "change", this.render);
        this.render();
    },

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

});

I am not sure what to write to listen to the last change and return that?

Does that sound clear, I'd be glad to re-elaborate or provide more code/fiddles.

Upvotes: 0

Views: 56

Answers (2)

Alex
Alex

Reputation: 1599

The change event that you listen to on the collection will contain the model that has changed, and the model has a previous() method that can be used to retrieve the previous value.

I've created this jsFiddle that I think does what you're after.

Upvotes: 1

tomas polach
tomas polach

Reputation: 163

render: function(model) {

    console.log(model.changed);
    // returns an object with all the changed values of the model
    // example: {points:5}

    console.log(model.previous('points'));
    // get the previous value for comparison

}

Upvotes: 0

Related Questions