Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - passing 2 models to 1 view

Tags:

backbone.js

I'm trying to pass 2 models to the view, but it seems it is not working. Here is my example: http://jsfiddle.net/kahhor/jp4B6/14/ As you can see second alert is showing undefined...

May be I have wrong approach. What I'm trying to do is: in View1 bind event 'change' to Model1... Than by clicking button in View2, call function in Model1 which changes value, and automatically render View1, since it was binded to change event.

But don't forget that View2 has also its own Model2, which I created outside the view and than passed it like new View2({model:Model2});.

It might looked confusing at first, but I think it is simple thing that backbone can do. I just don't know how to do it :)

Thanks,

like image 488
kaha Avatar asked Oct 12 '11 02:10

kaha


3 Answers

you can access custom parameters (options) from

window.PopupView = new PopupView({ model: LeftNotificationM, model2: PopupM});

like this:

window.PopupView = Backbone.View.extend({

    // code left out

    initialize: function () {
        this.model.bind('change:notification_num', this.render);
        alert(this.model);
        // your model2 option:
        alert(this.options.model2);
    },

   // code left out
});

Conclusion: "unrecognized options" of a view can be found in this.options

like image 153
sled Avatar answered Nov 03 '22 09:11

sled


I just found this question and Sled's answer via Google and it helped me a lot - but just to update this 2 year old question and perhaps save some other Googlers the headache:

Backbone Views no longer automatically attach options passed to the constructor as this.options, but you can do it yourself if you prefer.

Vitaliy's Answer on a similar question shows you how:

initialize : function (options) {
  this.options = options || {};
}
like image 35
Joel Avatar answered Nov 03 '22 09:11

Joel


Add this patch and pass any options directly to view.

    Backbone.View.prototype._configureWithoutThis = Backbone.View.prototype._configure;
    Backbone.View.prototype._configure = function(options) {
      this._configureWithoutThis(options);
      _.extend(this, this.options);
    }
like image 2
Alex Craft Avatar answered Nov 03 '22 07:11

Alex Craft