fancy
fancy

Reputation: 51393

Swap a view's model?

Basically I'm trying to figure out the best way to swap a model and react to that event.

class View extends Backbone.View
    initialize: ()->
        #do stuff
    swapModel: (newModel)->
        @model = newModel

view = new View({model:firstModel})

view.swapModel(newModel)

Is this all I have to do to swap out a view's model? Are there any other side effects I should plan for? What would be the best way to respond to this swap? Should I trigger a swap event in swapModel?

Thanks!

Upvotes: 2

Views: 775

Answers (3)

Rupert
Rupert

Reputation: 1639

You could use a collection that only allows one model. This way you don't touch the model and can call render as many times as you want. Something like this:

var SpecialCollection = Backbone.Collection.extend({
    swap: function (model) {
        //remove all models
        this.reset();
        //add one model
        this.add(model);
    }
});

var MyView = Backbone.View.extend({
    initialize: function(){
       this.listenTo(this.collection, 'add', this.render);
    },
    render: function() {
        this.model = this.collection.first()
        //do your normal rendering here
    }
});

var c = new SpecialCollection();
var v = new MyView({collection: c});
c.swap({name: 'Sam'});
//view should render
c.swap({name: 'Dave'});
//view should render

You could lock down the Collection rules a bit further but I think it serves as a good example to get you going.

Upvotes: 1

Derick Bailey
Derick Bailey

Reputation: 72868

Don't swap models in a view. You'll run in to all kinds of problems related to DOM event, Model events in the view, etc. I've tried to do this a dozen times or more, and in every single case, I re-wrote my code so that I would create a new view instance for each model. The code was cleaner, simpler, easier to understand and easier to maintain and work with.

Upvotes: 9

Sneaky Wombat
Sneaky Wombat

Reputation: 1848

A very simple example of one way to do it. Why are you trying to swap models though?

MyView = Backbone.View.extend({
    initialize: function() {

     this.myTrigger = {};
    _.extend(this.myTrigger, Backbone.Events);

    this.myTrigger.on("modelChange", function(msg) {
      alert("Triggered " + msg);
    },this);

    },
    swapModel: function(model) {
      // do something with model
      // then trigger listeners
      this.myTrigger.trigger("modelChange", "a model change event");
    }
});

var myview = new MyView()
myview.swapModel()

Upvotes: 1

Related Questions