Skip to content

Instantly share code, notes, and snippets.

@mbritton
Created June 22, 2012 13:55
Show Gist options
  • Save mbritton/2972867 to your computer and use it in GitHub Desktop.
Save mbritton/2972867 to your computer and use it in GitHub Desktop.
Backbone / jQM sketch
var productCollection = {};
var eventMediator = {};
var viewUtils = new utils();
window.products = new Products();
window.product;
window.CartView = Backbone.View.extend({
template : _.template(viewUtils.getTemplate('Cart')),
render : function(eventName) {
$(this.el).html(this.template());
return this;
},
});
window.CheckoutView = Backbone.View.extend({
template : _.template(viewUtils.getTemplate('Checkout')),
initialize : function(event) {
console.log('CheckoutView::initialize');
},
render : function(eventName) {
$(this.el).html(this.template());
return this;
},
});
window.HomeView = Backbone.View.extend({
template : _.template(viewUtils.getTemplate('Home')),
render : function(eventName) {
$(this.el).html(this.template());
return this;
},
});
window.ProductsView = Backbone.View.extend({
template : _.template(viewUtils.getTemplate('Products')),
events : {
//"all":"productSelected"
"click a" : "productSelected",
//"click a#foo" : "productSelected",
//"dblclick":"test",
//"tap":"test"
},
initialize : function(event) {
console.log('ProductsView::initialize');
this.collection = products;
this.collection.fetch({
url:'/bc_jquery_mobile/store_app_02/products.json',
success:this.populateProductsList
});
},
render : function(eventName) {
$(this.el).html(this.template());
return this;
},
productSelected : function(event) {
console.log('productSelected');
console.log($(event.target).attr('data-url'));
window.product = $(event.target);
console.dir(this.collection.get('p2'));
},
populateProductsList:function(data1, data2) {
console.log('populateProductsList');
$('#productListView').empty();
$.each(data2.products, function(i, item) {
$('#productListView').append('<li><a href="#productdetail" data-url="' + item.id + '"><h3>' + item.label + '</h3></a><a href="#" data-rel="dialog">Buy</a></li>');
});
$('#productListView').listview('refresh');
}
});
window.ProductdetailView = Backbone.View.extend({
template : _.template(viewUtils.getTemplate('ProductDetail')),
events : {
"click #addToCartButton" : "addToCart",
"click #checkoutButton" : "checkout",
},
initialize : function(event) {
console.log('ProductdetailView::initialize');
this.collection = products;
console.dir(window.product.attr('data-url'));
var ur = window.product.attr('data-url');
console.dir(this.collection.get(ur));
},
render : function(eventName) {
$(this.el).html(this.template());
return this;
},
addToCart : function(event) {
console.log('addToCart');
},
checkout : function(event) {
console.log('checkout');
app.checkout();
}
});
var AppRouter = Backbone.Router.extend({
routes : {
"" : "home",
"products" : "products",
"cart" : "cart",
"productdetail" : "productdetail",
"checkout" : "checkout",
//"checkout/:do_purchase" : "doPurchase"
},
initialize : function() {
// Handle back button throughout the application
$('.back').live('click', function(event) {
window.history.back();
return false;
});
this.firstPage = true;
},
cart : function() {
console.log('AppRouter::cart');
this.changePage(new CartView());
},
checkout : function() {
console.log('AppRouter::checkout');
this.changePage(new CheckoutView());
},
home : function() {
console.log('AppRouter::home');
this.changePage(new HomeView());
},
products : function() {
console.log('AppRouter::products');
this.changePage(new ProductsView());
},
productdetail : function() {
console.log('AppRouter::productdetail');
this.changePage(new ProductdetailView());
},
changePage : function(page) {
// Add the data-role attribute to the page element
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
var transition = $.mobile.defaultPageTransition;
// No transition on the first page
if(this.firstPage) {
transition = 'none';
this.firstPage = false;
}
$.mobile.changePage($(page.el), {
changeHash : false,
transition : transition
});
}
});
$(document).ready(function() {
console.log('...Application Ready...');
// Views, Routing
app = new AppRouter();
// Handle global events
eventMediator = _(eventMediator).extend(Backbone.Events);
eventMediator.bind("checkout", function() {
app.checkout();
});
Backbone.history.start();
});
@jonnyreeves
Copy link

Heya!

Modules

First observation would be that you're not separating your code into modules; I've personally be using RequireJS, there's a skeletal project structure available.

Don't have views Subscribe to Sync callbacks

In your ProductsView.initialize method you are invoking fetch on the products collection and updating the View via the success callback. Personally, I wouldn't have the view subscribe the callback and instead just bind to the collection's changed event. You can do this in your ProductsView.initialize method:

initialize: function () { 
    // ...snip...

    // Bind to the collection's `change` event, dispatched whenever the underlying collection
    // is modified.
    this.collection.on('change', this.onCollectionChanged);
}

Inject Collections and Models into Views

Instead of directly referencing which Model or Collection your view is going to work with, you can make use of constructor dependency injection in the AppRouter instead, eg:

products: function() {
    this.changePage(new ProductsView({ collection: products ));
}

This makes is easier to swap out dependencies and provides a small amount of decoupling between your view and model (more apparent when you have a modular application).

Equally, your ProductdetailView could have the Product model injected by the AppRouter instead of hitting the window global.

Make sure your views are being destroyed

ccoenraets Backbone jQuery Mobile implementation (which I presume you based your AppRouter off, doesn't call the jQuery Mobile page destructor; I modified the changePage method add an event listener and call page('destroy') at the appropriate time.

Hope these help! :)

@mbritton
Copy link
Author

How / when destroy() be called? Not sure I understand.

Also, do collections require me to manually add models, or does this happen automagically?

@jonnyreeves
Copy link

Hi Mike,

How / when destroy() be called? Not sure I understand.

It needs to be called during the changePage method. I modified the method to hold a reference to the fromPage (the one that was on the way out) and attach a listener for the pagehide event. You can then call the .page('destroy') method on the outgoing page in this event handler.

do collections require me to manually add models, or does this happen automagically?

You can either add models to a collection using the add method, or supply an initial collection of models in the Collection's constructor. Alternatively, backbone will take care of adding / modifying models when Backbone.sync is invoked on a collection (usually as the result of a fetch operation).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment