I want to build a simple backbone app for depositing and withdrawing funds via Stripe. Since a lot of the functionality is common, I placed that in a Stripe view, and extend the Deposit and Withdraw views from it, like so:
var App = {
Models: {},
Collections: {},
Views: {},
Router: {}
}
App.Views.Home = Backbone.View.extend({
el: $('#main-content'),
template: Handlebars.compile($('#home-template').html()),
render: function() {
this.$el.html(this.template())
return this
},
events: {
'click #deposit-button': 'navigateToDeposit',
'click #withdraw-button': 'navigateToWithdraw'
},
navigateToDeposit: function(e) {
Backbone.history.navigate('/deposit', true)
},
navigateToWithdraw: function(e) {
Backbone.history.navigate('/withdraw', true)
}
})
App.Views.Stripe = Backbone.View.extend({
el: $('#main-content'),
initialize: function() {
Stripe.setPublishableKey('pk_test_0QvQdPBkXAjB4EBsT4mf226x')
},
render: function() {
this.$el.html(this.template())
return this
},
events: {
'click #submit': 'submitForm'
},
submitForm: function(e) {
e.preventDefault()
$('#submit').prop('disabled', true)
var that = this
Stripe.card.createToken($('#form'), that.stripeResponseHandler)
},
stripeResponseHandler: function(status, response) {
var $form = $('#form')
if(response.error) {
$form.find('.payment-errors').text(response.error.message)
$('submit').prop('disabled', false)
} else {
console.log(this)
var form_data = this.getFormData(response.id),
that = this
$.post(that.transaction_endpoint, form_data, function(data, textStatus, jqXHR) {
Backbone.history.navigate('/home', true)
})
}
}
})
App.Views.Deposit = App.Views.Stripe.extend({
template: Handlebars.compile($('#deposit-template').html()),
getFormData: function(token) {
return {
amount: $('#form input[name=amount]').val(),
token: token
}
},
transaction_endpoint: 'handledeposit'
})
App.Views.Withdraw = App.Views.Stripe.extend({
template: Handlebars.compile($('#withdraw-template').html()),
getFormData: function(token) {
return {
name: $('#form input[name=name]').val(),
email: $('#form input[name=email]').val(),
token: token
}
},
transaction_endpoint: 'handlewithdraw'
})
App.Router = Backbone.Router.extend({
routes: {
'deposit' : 'showDepositView',
'withdraw' : 'showWithdrawView',
'*path' : 'showHomeView'
},
showDepositView: function() {
var depositView = new App.Views.Deposit()
depositView.render()
},
showWithdrawView: function() {
var withdrawView = new App.Views.Withdraw()
withdrawView.render()
},
showHomeView: function() {
var homeView = new App.Views.Home()
homeView.render()
}
})
var router = new App.Router()
Backbone.history.start()
The call to the getFormData method gives me an error saying the function is undefined, even though I have defined it in both Deposit and Withdraw views. Also, I added a console.log(this) right above it, and it logs the Window object to the console instead of the View. What am I doing wrong here?
I have a feeling it's to do with this call:
Stripe.card.createToken($('#form'), that.stripeResponseHandler)
Try binding this to the calling scope using .bind():
Stripe.card.createToken($('#form'), that.stripeResponseHandler.bind(this))
You don't really need to do var that = this but I'll leave it in for simplicity's sake.
Related
I'm trying to create a module using Backbone.js, but I'm getting the error Javascript Error: Uncaught TypeError: autoAuth.View is not a constructor.
Auth.js.erb
(function(app, Auth){
var game = app.module('game');
Auth.View = Backbone.View.extend({
el: '.js-auth',
cssClass: 'auth',
events: {
'click .js-popup': 'popupLogin',
'click .js-login-with-email': 'emailLogin',
'click .js-tos-modal': 'tosModal',
'click .js-privacy-modal': 'privacyModal',
'click .js-auto-login': 'autoLogin'
},
template: Handlebars.compile(
<%= embed('../templates/auth.hbs').inspect %>
),
initialize: function() {
Handlebars.registerPartial('login-buttons',
<%= embed('../templates/login-buttons.hbs').inspect %>
);
},
render: function() {
_.extend(this.options, {
skipOnboarding: game.player.get('skip_onboarding'),
claimableIncentive: game.incentive.get('claimable'),
claimableAmount: game.incentive.get('amount'),
});
this.$el.addClass(this.cssClass);
this.$el.html(this.template(this.options));
growth.urlChangeNotification();
},
popupLogin: function(event) {
event.preventDefault();
event.stopPropagation();
this.validateLogin(_.partial(popupLogin, event));
},
emailLogin: function(event) {
this.validateLogin(_.partial(this.emailAuth, event));
},
autoLogin: function(event) {
this.validateLogin(_.partial(this.autoAuth, event));
},
validateLogin: function(callback) {
if (this.$el.find('#agree-to-tos').is(':checked')) {
callback();
} else {
this.$el.find('.js-tos-error').show();
}
},
emailAuth: function(view_option, value) {
var emailAuth = app.module('emailAuth');
var emailAuthView = new emailAuth.View;
if (_.isString(view_option)) {
emailAuthView.setViewOption(view_option);
if (view_option === 'reset') {
game.user.set('reset_password_token', value);
}
}
emailAuthView.openModal({
allowCancel: view_option !== 'reset'
});
emailAuthView.render();
},
autoAuth: function(view_option, value) {
var autoAuth = app.module('autoAuth');
var autoAuthView = new autoAuth.View;
if (_.isString(view_option)) {
autoAuthView.setViewOption(view_option);
}
autoAuthView.openModal({
allowCancel: view_option !== 'reset'
});
autoAuthView.render();
},
tosModal: function() {
var modal = new Backbone.BootstrapModal({
content: <%= embed('../templates/terms-of-service.hbs').inspect %>
}).open();
},
privacyModal: function() {
var modal = new Backbone.BootstrapModal({
content: <%= embed('../templates/privacy-policy.hbs').inspect %>
}).open();
}
});
})(app, app.module('auth'));
AutoAuth.js.erb
function(app, AutoAuth)(
var game = app.module('game');
AutoAuth.View = ModalView.extend({
view_modes: ['login'],
template: Handlebars.compile(
<%= embed('../templates/auto-auth.hbs').inspect %>
),
events: {
'submit #email-login': 'logIn',
'click #login': function() {
this.setViewOption('login');
this.render();
},
},
genericErrorMessage: 'Oops something went wrong! Please contact support.',
initialize: function(options) {
var self = this;
this.options = options || {};
this.setViewOption('login');
_.bindAl(this, 'login');
game.user.on({
signin_sucess: function(){
self.reloadPage();
},
signin_error: function(data) {
self.options.error = false;
self.setViewOption('login');
var error = 'Unable to sign in with the given email and password.';
if (data && data.error) { error = data.error; }
self.options.signin_error = error;
self.render();
},
})
},
setViewOption: function(view) {
var self = this;
_.each(self.view_modes, function(k) {
self.options[k] = false;
});
self.options[view] = true;
},
render: function(){
this.$el.html(this.template(this.options));
if (mobile) window.scrollTo(0, 1); // hack for modals on mobile
this.delegateEvents();
this.clearErrors();
var authPage = _.chain(this.options)
.pick(function(value, key) { return value; })
.keys()
.value()[0];
growth.urlChangeNotification();
},
logIn: function(e) {
e.preventDefault();
this.options.email = this.$('#login_email').val();
if (!validateEmail(this.options.email)) {
this.options.signin_error = 'Must enter a valid email address.';
this.render();
return;
}
game.user.signIn({
email: this.options.email,
password: this.$('#login_password').val(),
remember_me: true
});
},
reloadPage: function() {
window.location = window.location.href.substr(0, window.location.href.indexOf('#'));
}
});
})(app, app.module('authAuth'));
Do you have this error on the line with var autoAuthView = new autoAuth.View; ?
To create a new instance of autoAuth.View you need to do var autoAuthView = new autoAuth.View();.
autoAuth.View is the class, to call the contructor, and create a new instance, you need to call it with ().
Is it possible to handle F5 button in Backbone? Something like:
events: {
'click .btn': 'function1'
}
Actually I have problem with destroying models after refresh. I get error, when the method get("title") is invoking. And this is App.js. And I thought to create new function after refresh event.
var App = (function () {
var api = {
Views: {},
Models: {},
Collections: {},
Content: null,
Router: null,
init: function () {
Backbone.history.start();
return this;
}
};
var ViewsFactory = {
view1: function () {
api.Models.Model1 = new Model1();
if (!this.View1) {
this.View1 = new api.Views.View1({
el: $(".content"),
model: api.Models.Model1
}).on("trigger1", function () {
api.Models.Model1 = this.model;
api.Router.navigate("#test", {trigger: true});
});
}
return this.View1;
},
view2: function () {
api.Collections.Collection1 = new Collection1();
var test = new Model2({
title: api.Models.Model1.get("title"),
collection: api.Collections.Collection1
});
return this.View2 = new api.Views.View2({
el: $(".content"),
model: test
});
}
};
var Router = Backbone.Router.extend({
routes: {
"": "view1",
"test": "view2"
},
view1: function () {
var view1 = ViewsFactory.view1();
view1.render();
},
view2: function () {
var view2 = ViewsFactory.view2();
view2.render();
}
});
api.Router = new Router();
return api;
})();
I handle this by router and "" route.
I know Im pretty close to figuring this out. Im trying to filter out my collection based on if favorite eq true. If I console.log - I can see it's doing its job. But it's not updating my view.
Anyone have any idea what I'm missing or doing wrong?
Here is my code:
var Products = Backbone.Model.extend({
// Set default values.
defaults: {
favorite: false
}
});
var ProductListCollection = Backbone.Collection.extend({
model: Products,
url: '/js/data/wine_list.json',
parse: function(data) {
return data;
},
comparator: function(products) {
return products.get('Vintage');
},
favoritesFilter1: function(favorite) {
return this.filter(function(products) {
return products.get('favorite') == true;
});
},
favoritesFilter: function() {
return this.filter(function(products) {
return products.get('favorite') == true;
});
},
});
var products = new ProductListCollection();
var ProductListItemView = Backbone.View.extend({
el: '#wine-cellar-list',
initialize: function() {
products.bind('reset', this.render, this);
products.fetch();
this.render();
},
render: function() {
console.log(this.collection);
var source = $('#product-template').html();
var template = Handlebars.compile(source);
var html = template(this.collection.toJSON());
this.$el.html(html);
return this;
},
});
// Create instances of the views
var productView = new ProductListItemView({
collection: products
});
var CellarRouter = Backbone.Router.extend({
routes: {
'': 'default',
"favorites": "showFavorites",
"purchased": "showPurchased",
"top-rated": "showTopRated",
},
default: function() {
productView.render();
},
showFavorites: function() {
console.log('Favorites');
productView.initialize(products.favoritesFilter());
},
showPurchased: function() {
console.log('Purchased');
},
showTopRated: function() {
console.log('Top Rated');
}
});
$(function() {
var myCellarRouter = new CellarRouter();
Backbone.history.start();
});
There's many mistakes in your code, I'll try to clarify the most I can :
Your collection should be just like this :
var ProductListCollection = Backbone.Collection.extend({
model: Products,
url: '/js/data/wine_list.json',
comparator: 'Vintage' // I guess you want to sort by this field
});
Your view like this :
var ProductListItemView = Backbone.View.extend({
el: '#wine-cellar-list',
initialize: function() {
this.collection.bind('reset', this.full, this);
this.collection.fetch();
},
full: function() {
this.render(this.collection.models);
},
favorites: function(favorite) {
this.render(this.collection.where(favorite)); // here's the answer to your question
},
render: function(models) {
console.log(models);
var source = $('#product-template').html();
var template = Handlebars.compile(source);
var html = template(models.toJSON()); // You may have to change this line
this.$el.html(html);
return this;
},
});
And in your router :
showFavorites: function() {
console.log('Favorites');
productView.favorites(true); // or false, as you like
}
I've created 2 separate views, 1 to render the template and the other one is where I bind the events, then I tried merging them into one in which case it causes an Uncaught TypeError: Object [object Object] has no method 'template'. It renders the template and the events are working as well, but I get the error.
edit.js, this is the combined view, which I think it has something to do with their el where the error is coming from
window.EditView = Backbone.View.extend ({
events: {
"click #btn-save" : "submit"
},
initialize: function() {
this.render();
},
render: function() {
$(this.el).html(this.template());
return this;
},
submit: function () {
console.log('editing');
$.ajax({ ... });
return false;
}
});
var editView = new EditView();
signin.js, this is the view that I can't merge because of the el being used by the ajax call and in SigninView's $(this.el) which causes the rendering of the templates faulty
window.toSigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
initialize: function() {
console.log('Signin View');
},
submit: function() {
$.ajax({ ... });
return false;
}
});
var toSignin = new toSigninView();
window.SigninView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
$(this.el).html(this.template());
return this;
}
});
and I use utils.js to call my templates
window.utils = {
loadTpl: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (window[view]) {
deferreds.push($.get('templates/' + view + '.html', function(data) {
window[view].prototype.template = _.template(data);
}));
} else {
alert(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}
};
In my Router.js, this is how I call the rendering of templates
editProfile: function() {
if (!this.editView) {
this.editView = new EditView();
}
$('#global-container').html(this.editView.el);
},
utils.loadTpl (['SigninView', 'EditView'],
function() {
appRouter = new AppRouter();
Backbone.history.start();
});
I think that I figured out your problem.
First merge your views and delete the line var toSignin = new toSigninView();
Second modify your utils.js code like this :
window[view].prototype.template = _.template(data);
new window[view]();
I am getting an
Object function (a){return new n(a)} has no method 'has'
error on calling the fetch() method on my model. Heres the code:
var Exercise = Backbone.Model.extend({
defaults: {
idAttribute: 'e_id',
e_id: "-1",
exerciseName: "Exercise",
exerciseDescription: "Address",
exerciseURL: "vimeo.com",
reps: "0",
sequence: "0"
},
initialize: function() {
alert("Exercise!");
}
});
var ExerciseList = Backbone.Collection.extend({
url: "/getWorkoutList.php",
model: Exercise,
initialize: function() { }
});
var Workout = Backbone.Model.extend({
urlRoot: "/getWorkoutList.php",
url: function() {
return this.urlRoot + "?workoutID=" + this.get('workoutId');
},
defaults: {
idAttribute: 'workoutId',
workoutId: "-1",
workoutName: "WorkoutName",
workoutDescription: "WorkoutDescription",
exercises: new ExerciseList()
},
initialize: function() {
_.bindAll(this);
directory.renderWorkout(this);
},
parse: function(response) {
return response;
}
});
var WorkoutList = Backbone.Collection.extend({
url: "/getWorkoutList.php",
model: Workout,
initialize: function() {
_.bindAll(this);
},
parse: function(response) {
return response;
}
});
var WorkoutView = Backbone.View.extend({
tagName: "div",
className: "workout-container",
template: $("#tmp-workout").html(),
initialize: function() {
_.bindAll(this);
this.model.bind('change', this.render, this);
},
render: function(){
console.log("WorkoutView");
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
},
//add ui events
events: {
"click #workout-details": "getWorkoutDetails"
},
getWorkoutDetails: function (e) {
e.preventDefault();
this.model.fetch();
}
});
var ExerciseView = Backbone.View.extend({
tagName: "exercise",
className: "exercise-container",
template: $("#tmp-exercise").html(),
initialize: function() {
_.bindAll(this);
alert("ExerciseView");
},
render: function(){
console.log("render exercise view");
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
var WorkoutListingView = Backbone.View.extend({
el: $("#workouts"),
initialize: function() {
var collection = new WorkoutList();
collection.fetch();
},
render: function() {
var that = this;
_.each(this.collection.models, function(item){
that.renderWorkout(item);
});
},
renderWorkout: function(item) {
var workoutView = new WorkoutView({
model:item
});
this.$el.append(workoutView.render().el);
var that = this;
_.each(workoutView.model.get('exercises').models, function(exercise) {
that.renderExercise(exercise);
});
},
renderExercise: function(item) {
var exerciseView = new ExerciseView({
model:item
});
this.$el.append(exerciseView.render().el);
}
});
Everything works fine when I am retrieving the Workout Collection the fist time. However, when I call getWorkoutDetails, I get the error. By inserting alerts and console.logs in parse() of Workout Model, I've found out that it does get the correct response from server, but for some reason, its giving this error.
Any ideas? Thanks.
OK, after spending a lot of time in the beautiful world of minified javascript spaghetti, I found out that the underscore.js version I was using didnt had the function 'has' in it. Updating underscore.js from 1.2.2 to 1.4.4 solved the problem. Also, my backbone.js version is 0.9.1