1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
With this in place, it means that any time our Backbone model is changed, the view will be updated to reflect that. In this example we have used a Post view and model, but models can represent any resource. When
post.fetch() returns, a “change” event is triggered, this event is being listened for on the view, and when it occurs,
render() in the view is called. This style of event binding also means that when a save is called, the view is also re-rendered. This all works well for a single person editing the posts, but what about if we want multiple people to be able to edit the resource, and all others to be notified?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
With this in place, any time an event happens on the “post1” channel, a backbone event will be triggered. We can now listen to this event in the
initialize function of the model.
1 2 3 4 5 6 7 8
Unfortunately we can’t just call fetch when we receive a “post:change” event as the date received from Pusher is an array, and Backbone is expecting an object. I did try to patch this but it was not accepted, so we need to wrap the
fetch() inside another function.
The last thing required to hook this up is to trigger an event when the model is saved. This depends on your backend however you can also trigger these from the Pusher dashboard on their website after you have signed in, the name of the message you want to send is “post:change”. Using the Pusher gem and Ruby on Rails, you would do:
Everything is now hooked up. You will notice that if you have your application open in two browsers, when you update one, the other will automatically update. When a “post:change” event is received from Pusher, the model is listening for it and triggers a
fetch() which in turn triggers a
render() on the view.
This is just one way of doing things of course, you can also send data through with your event to prevent performing an additional
fetch() on the server. You can also bind the notifier to Backbone Views and Collections and perform any functions you wish when an event is received.