steo
steo

Reputation: 4656

Bind Model to a View asynchronously in Backbone

my problem is to bind a model, that I istanciate at certain time during my application, to a View that has been created at initialization time. Let me explain better:

In my route I istanciate a View:

...
var view = new app.FirstView();
view.render();

In

app.FirstView = Backbone.View.extend({

   initialize: function(){
     ...
     this.SidebarView = new app.SidebarView(); 
   }
... });

At certain time X during my application I have this behaviour in an another view:

app.AnotherView = Backbone.View.extend({
   ...
   onClickHandler: function(){
      var aModel = app.aModel();
      var view = app.aView({ model: aModel });
   }
})

My problem now, is to bind aModel defined in the onClickHandler to SidebarView which I created and bounded to the FirstView at initialization time.

Please tell me if something is not clear.

Thanks in advance

Upvotes: 0

Views: 29

Answers (1)

StateLess
StateLess

Reputation: 5402

one solution is to use an event for example,

In your AnotherView trigger a event and pass to model to View

 onClickHandler: function(){
      var aModel = app.aModel();
      Backbone.trigger('model:assigned',aModel);
   }

in your sidebarView's initialize you should listen for event

Backbone.on("model:assigned",function(passedModel){
   this.model = passedModel; 
})

Note1: You must be sure that sidebarView is initialized by the time you are triggering event.

Note2: Try avoiding Global events , i used as i don't know your code structure.

Upvotes: 2

Related Questions