Alex Rivera | Logout

Raising a Backbone.js View event

Asked 2012-02-19T16:03:12.463
19

I'd like to find a way to raise a backbone.js "event" without something having changed in the model or in the dom.

For instance, I'm loading the Facebook SDK asynchronously. I'm subscribed to the auth.login event, and would like to send a message to my view that the user has logged in so it can re-render itself appropriately.

My view looks similar to this:

window.CreateItemView = Backbone.View.extend({
  el: $('#content'),
  initialize: function() {
    this.render();
  },
  render: function() {
    // do something
    return this;
  },
  setSignedRequest: function(signedRequest) {
    //do something with signedRequest
  }
});

In my facebook code, I do this:

  FB.Event.subscribe('auth.login', function(response){
    if (response.status === 'connected') {
      var uid = response.authResponse.userID;
      var accessToken = response.authResponse.accessToken;
      window.signedRequest = response.authResponse.signedRequest;

      if (window.view && window.view.setSignedRequest) {
          window.view.setSignedRequest(window.signedRequest);
      }
    }
  });

However, while window.view exists, it cannot see the setSignedRequest method. I've ensured that my scripts are loading in the correct order. Strangely I have this same code on a different page albeit a different View object and it works fine. I haven't seen any difference that would account for this.

A better solution would be to raise some sort of event and have the view listen for it. However, I don't want to utilize the change event on the model as the signedRequest shouldn't be a property of the model. Is there a better way of accomplishing this?

Edit
Report

1 Answer

11

If you want to do that outside your model and subscribe to the event on your view you could do the following:

var SomeObject = {...};
_.extend(SomeObject, Backbone.Events);

Then, you can subscribe to events on SomeObject

SomeObject.on('myevent', someFunc, this);

or trigger the event

SomeObject.trigger('myevent', data);
answered 2012-02-19T16:16:08.350

Your Answer