Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising a Backbone.js View event

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?

like image 995
James Avatar asked Feb 19 '12 16:02

James


2 Answers

Backbone.View is extended with Backbone.Events which means you can easily trigger custom events and pass whatever data you want

var View = Backbone.View.extend({

    initialize: function() {

        this.on('customEvent', this.doSomething, this);
    }

    doSomething: function(someData) {

        // this!
    }
});

var view = new View();

view.trigger('customEvent', "someDataHere");

though I don't know why you can't see the method on the view - it should work - Are you 100% sure you are instantiating the view correctly? and that window.view is instance of CreateItemView ?

like image 165
Tom Tu Avatar answered Oct 21 '22 09:10

Tom Tu


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);
like image 11
ggozad Avatar answered Oct 21 '22 09:10

ggozad