Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've used Google DoubleClick for Publishers on a number of my sites and when it came to thinking about monetising my new project (AtariGamer) that was my goto choice once again. However, compared to my previous approaches, I wanted to do things differently over at AtariGamer. My goal was to try and use well established web app frameworks as much as possible and so I decided to use Backbone.js for all dynamic UI generation. This was to include all of the ads. I also used jQuery to make some things simpler.

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...
 HTML body
<script type="text/template" id="ad-template">
<div id="<%- id %>"></div>
</script>


That's all there's to it! The template of course goes somewhere inside the HTML body element.

Next up is the JavaScript for the Backbone model and view. These take care of encapsulating configuration and ad data and also generating ad elements for rendering,
 JavaScript
DfpAdModel = Backbone.Model.extend({
defaults: function() {
/* update pubId, adUnitCode and size to suit your DFP account details */
this.set('pubId', '12345678');
this.set('adUnitCode', 'MyAdUnit');
this.set('size', [728, 90]);
/* don't change the id */
this.set('id', 'dfpslot' + DfpAdModel.dfpSlotId++);
},
dfp: function() {
var adUnitPath = '/' + this.get('pubId') + '/' + this.get('adUnitCode');
var adSize = this.get('size');
var id = this.get('id');
if (typeof googletag !== 'undefined') {
googletag.cmd.push(function() {
var slot = googletag.defineSlot(adUnitPath, adSize, id)
.addService(googletag.pubads());
googletag.display(id);
googletag.pubads().refresh([slot]);
});
}
}
},
{ dfpSlotId: 1 }
);
DfpAdView = Backbone.View.extend({
tagName: 'div',
template: _.template($('#ad-template').html()),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});




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...
 JavaScript
var model = new DfpAdModel();
$('body').append((new DfpAdView( { model: model })).render().el);
model.dfp();


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.

-i

Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...
Hi! You can search my blog here ⤵
Or browse the recent top tags...

Recent Blog Posts

How to fix Google Cloud SDK dev server error - No module named ipaddr

Adorable but totally metal - Metal Earth 3D Guardians of the Galaxy Groot model kit

Riverside Expressway Cam shut down permanently

Inserting Google DFP ads with Backbone, Underscore and jQuery

How to resolve the domain is already mapped to a project error in Google App Engine

A quick look at the Nyko Super MiniBoss wireless controllers for the SNES mini

Loading and displaying a collection from bootstrapped data in Backbone.js

Add this handy function to your Bash profile file to display the compiled JDK version for a .class file

How does PCBWay stack up as a low budget PCB fab

Resolving the Cannot reference X before supertype constructor is called compiler error in Java

Recent Galleries

BMB-012 Nanoblock T-Rex Skeleton Model assembly

Tiny Arcade revision 6 kit assembly and decal application

Atari Lynx repair - Part 5 - McWill LED screen mod installation

Atari Lynx repair - Part 4 - screen cover replacement

Atari Lynx repair - Part 2 - re-capping the motherboard

Atari Lynx repair - Part 3 - broken speaker replacement

Atari Lynx repair - Part 1 - introduction and case disassembly

Building a custom Atari Lynx game box storage shelf unit in a day

Protecting old Atari Lynx game boxes with snug fit plastic sleeves

Monument Valley 2 is released and does not disappoint

Blogs and Friends

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity