To get DFP ads working with Backbone.js I had to create a template, model and a view. My first implementation of this failed spectacularly due to DFP's use of closures for its command execution. I learned from that mistake and rewrote the code and came up with something that worked pretty well.
The DFP reference was useful documentation in helping me resolve the issues I came across. In this article I will not cover basics such as setting up ad units or adding the googletag code to your pages - these are covered in my previous articles: How to use Google AdSense on infinite scroll web pages and Using Google DFP with AdSense on responsive pages. Have a look at those to get up to speed if you're not familiar with DFP.
So lets first look at the template. I've simplified this one from my actual implementation (I require the use of tables for ads over at AtariGamer). This template keeps things simple and down to the bare essentials. Here it is...
That's all there's to it! The template of course goes somewhere inside the HTML body element.
The model takes care of storing DFP account details and keeping track of the ad slot ID. This is also where the googletag code is placed. The slot ID is kept track of by using a static variable and incrementing it each time a new model is created. This way each new instance of a model gets a unique slot ID assigned.
The view simply looks up the template, passes it the model and creates the HTML elements required.
So that's the template, model and view all taken care of. What's left is making it all work together and adding it to the DOM. For that my code looks something like this...
The code above creates a new model and view and appends it to the HTML body. The view can of course be inserted anywhere else in the DOM, it's just simpler to use $('body') for this example. Once the view is added, the dfp() function is called on the model to execute the googletag code that fetches and renders the ad.
This code can be repeated anywhere else a new DFP ad (in a new ad slot) should be added. This is great for infinite scroll pages or pages where ads need to be inserted at regular intervals. I've also used it on some pages with static content simply because it was easy to insert ads this way.
Add CSS to suit and you've got a very reusable Backbone.js model and view that will let you insert DFP ads with ease.