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?
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
?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With