href javascript button not showing - javascript

I am implementing a share function in my javascript. but the button link doesn’t appear, I’m really a beginner and researched but I couldn’t find out where I’m wrong, the button link just doesn’t appear, there’s no error log on my console. I am really lost if someone can help me I am grateful.
Before opening this question, I saw all the questions related to the same problem, but none were successful in my case.
$(document).ready(function() {
function sharefbimage() {
FB.init({ appId: `XXXXXX`, status: true, cookie: true });
FB.ui(
{
method: `share`,
name: 'Facebook Dialogs',
href: $(location).attr('href'),
link: 'https://developers.facebook.com/docs/dialogs/',
picture: 'your image url',
caption: 'Ishelf Book',
description: 'your description'
},
function (response) {
if (response && response.post_id) {
alert('success');
} else {
alert('error');
}
}
)};
$(".result").on("click", function() {
var id = $(this).attr("data-linkId");
var url = $(this).attr("href");
if(!id) {
alert("data-linkId attribute not found");
}
increaseLinkClicks(id, url);
return false;
});
var grid = $(".imageResults");
grid.on("layoutComplete", function() {
$(".gridItem img").css("visibility", "visible");
});
grid.masonry({
itemSelector: ".gridItem",
columnWidth: 200,
gutter: 5,
isInitLayout: false
});
$("[data-fancybox]").fancybox({
caption : function( instance, item ) {
var caption = $(this).data('caption') || '';
var siteUrl = $(this).data('siteurl') || '';
var sharefbimage = $(this).data('siteurl') || '';
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '')
+ 'View image<br>'
+ 'Visit page';
+ 'share';
}
return caption;
},
afterShow : function( instance, item ) {
increaseImageClicks(item.src);
}
});

Try this.
if ( item.type === 'image' ) {
caption = (caption.length ? caption + '<br />' : '')
+ 'View image<br>'
+ 'Visit page<br>'
+ 'Share';
}

Related

Integrating Braintree Client token into braintree.client.create

I have limited experience working with JavaScript and am attempting to pass a client token generated on my server into the braintree client create of Braintree's javascript code. I do not know how to pass the ClientToken out of the jQuery post and into the authorization section of braintree.client.create. A portion of my code is below:
<script src="https://js.braintreegateway.com/web/3.34.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/hosted-fields.min.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/paypal-checkout.min.js"></script>
<script>
var form = document.querySelector('#register-form');
var submit = document.querySelector('input[type="submit"]');
var ClientToken;
var authPosting = jQuery.post('/path/to/php_scripts/getClientToken.php');
authPosting.done(function( data ) {
ClientToken = data;
console.log(ClientToken);
});
braintree.client.create({
authorization: 'ClientToken'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '15px',
'font-family': 'roboto, verdana, sans-serif',
'font-weight': 'lighter',
'color': 'black'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': 'black'
},
'.invalid': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: ''
},
cvv: {
selector: '#cvv',
placeholder: ''
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
selector: '#postal-code',
placeholder: ''
}
}
}, function(err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
function findLabel(field) {
return jQuery('.hosted-field--label[for="' + field.container.id + '"]');
}
hostedFieldsInstance.on('focus', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).addClass('label-float').removeClass('filled');
jQuery(".error-msg").hide();
});
// Emulates floating label pattern
hostedFieldsInstance.on('blur', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isEmpty) {
label.removeClass('label-float');
} else if (field.isValid) {
label.addClass('filled');
} else {
label.addClass('invalid');
}
});
hostedFieldsInstance.on('empty', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).removeClass('filled').removeClass('invalid');
});
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isPotentiallyValid) {
label.removeClass('invalid');
} else {
label.addClass('invalid');
}
});
//Submit function
jQuery("#register-form").validate({
submitHandler: function(form) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
if (err.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
var msg = "All credit card fields are required.";
jQuery(".error-msg").text(msg);
jQuery(".error-msg").show();
} else if (err.code === 'HOSTED_FIELDS_FIELDS_INVALID') {
var invalidFields = err.details.invalidFieldKeys;
invalidFields.forEach(function (field) {
if (field == "number") {
var myid = "card-number";
var myobj = "credit card number";
} else if (field == "expirationDate") {
var myid = "expiration-date";
var myobj = "expiration date";
}
jQuery("#" + myid).append("<div class='error-msg'>Please enter a valid " + myobj + ".</div>");
});
} else {
var msg = "There was an error on the form."
alert (msg);
}
return;
}
vfirst = jQuery( "input#firstname" ).val(),
vlast = jQuery( "input#lastname" ).val(),
vemail = jQuery( "input#email" ).val(),
vproof = jQuery( "input[name='proof']" ).val(),
vprice = jQuery( "tr#total td.price" ).data('price'),
vcourse = 1950,
vnonce = 'fake-valid-nonce',
url = '/path/to/php_scripts/placeOrder.php';
// This is where you would submit payload.nonce to your server
// alert('Submit your cc nonce to your server here!');
});
//form.submit();
}
});
});
....more code below....
</script>
Any suggestions would be greatly appreciated.
Answering my own question:
CLIENT_AUTHORIZATION = jQuery.parseJSON(jQuery.ajax({
url: "/path/to/php_scripts/TokenScript.php",
dataType: "json",
async: false
}).responseText);
braintree.client.create({
authorization: CLIENT_AUTHORIZATION.token
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
} code continues.....
The CLIENT_AUTHORIZATION.token is whatever the token was named on the client authorization script.

Jquery .click event doesn't fire what could be the cause?

I have the following jquery script in a Razor view with layout set to the null.
<script type="text/javascript">
jQuery(document).ready(function () {
$('#shareapp').click(function () {
check_if_fb_is_defined();
});
window.fbactivity_id = '#Model.Id';
window.fbactivity_name = 'your-hollywood-movie';
window.wallpost_name = 'How would be your hollywood movie poster look like ?';
window.wallpost_picture = '#ViewBag.ImageURL';
window.wallpost_description = 'How would be your hollywood movie poster look like?';
window.wallpost_link = '#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL })))';
window.wallpost_caption = 'Ozhay';
window.tags = 'Naser';
function check_if_fb_is_defined() {
if (typeof (FB) === 'undefined') {
fbsharer();
} else {
PostShare('#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL})))';
}
}
function PostShare(mylink) {
FB.ui({
method: 'share',
href: mylink,
hashtag: '#Ozhay',
}, function (response) {
if (response && !response.error_message) {
ga('send', 'event', 'Wallpost', 'Facebook', window.fbactivity_name, window.fbactivity_id);
} else {
ga('send', 'event', 'Wallpost', 'No', window.fbactivity_name, window.fbactivity_id);
}
});
}
//if FB is undefined
function fbsharer() {
ga('send', 'event', 'Dialog', 'Facebook', window.fbactivity_name, window.fbactivity_id);
window.fb_sharer_url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(window.wallpost_link);
window.popupWindow = window.open(window.fb_sharer_url, 'facebooksharer', 'height=567,width=572');
var popupTimer = window.setInterval(function () {
if (typeof window.popupWindow !== 'undefined') {
if (window.popupWindow.closed !== false) {
window.clearInterval(popupTimer);
}
}
}, 200);
}
})
</script>
I have added Jquery script file to the view but for whatever reason When I click on a link that has shareapp id nothing happens. This is a bit strange to me where sometimes before it worked. your thoughts about this?
FB is undefined - where do you declare FB?
function check_if_fb_is_defined() {
if (typeof (FB) === 'undefined') {
fbsharer();
} else {
Syntax error - Need ')' before ';' at end of PostShare.
PostShare('#Html.Raw(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority,Url.Action("campaign_result", "facebook", new { #resultid = Model.Id, #imgURL = ViewBag.ImageURL})))';
}
}
})

Error with Knockout-validation validation

I have a collection of text editors in a form, validating them with knockout-validation. When I submit the form, only a few of them show validation errors, although all of them should pass. This issue only occurs with these two fields shown in error, however I have checked and double checked and all of the wiring for all of these is set up correctly, e.g. there is no reason I can see that these two fields should be different from the others that do not exhibit this issue.
I'm hoping that someone with more experience than I in the internals of knockout-validation could point me to something that may be alternately tripping the validation of these. I have it set up to validate the text when a user clicks outside of the editor, and that works fine. The issue below only appears when a user clicks submit, and other fields on the page (besides the editors shown here) have an issue. In other words, if every single field is valid, the form is submitted. If any fields OTHER than those shown below have issues, the false positive is shown.
Adding Code examples:
Creating the validator and extending the observables. Note the ones depicted in the image are configured identically to those not being marked invalid:
ko.validation.rules['notIn'] = {
validator: function (value, params) {
var thisValidator = baseCompare.slice();
if (Array.isArray(params))
params.forEach(function (element, index, array) {
thisValidator.push(element);
});
else
thisValidator.push(params);
return thisValidator.indexOf(value) == -1;
},
message: 'Please enter a unique value'
};
ko.validation.registerExtenders();
self.setupValidation = function () {
self.title.extend({
required: true,
notIn: {
message: 'Please enter a unique title',
params: self.froalaBasify('New Change Request')
}
});
self.domain.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.priority.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.securityClassification.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.impact.extend({ required: true, notEqual: '0' }).extend({ notify: 'always' });
self.customersAffected.extend({
required: true,
notIn: {
message: 'Please describe the customers affected',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.customersAffected)
}
});
//False Positive
self.justification.extend({
required: true,
notIn: {
message: 'Please provide a justification for the request',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.justification)
}
});
self.scope.extend({
required: true,
notIn: {
message: 'Please describe the systems affected by this change',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.scope)
}
});
//False Positive
self.validationProcess.extend({
required: true,
notIn: {
message: 'Please enter a validation plan for this change',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.validationProcess)
}
});
self.description.extend({
required: true,
notIn: {
message: 'Please enter a description',
params: self.froalaBasify(CRHelper.ValidationPlaceholders.description)
}
});
self.deadlineRequested.extend({
required: true,
dateGreaterThanToday: {
onlyIf: function () {
//var isTrue = $('#ddTransition option:selected').text() == "Delete Request";
//return !(isTrue);
return self.id === 0;
}
}
});
//self.deadlineRequested.extend({
// required: true}).extend({ notify: 'always' });
};
And then here is the submit handler:
self.submitChangeRequest = function () {
var validated = ko.validatedObservable(self.ChangeRequest());
var transition = "";
transition = $('#ddTransition option:selected').text();
var disableValidation = false;
if (transition == "Delete Request")
disableValidation = true;
var formIsValid = validated.isValid();
if (CRHelper.ConfirmSubmitIfDeleteChosen() && (disableValidation || formIsValid)) {
$('.submitter').prop('disabled', true);
var formUsage = $("[id*='hdnFormUsage']")[0].value;
var ajax = new utils.AjaxFormatter(
{
type: "POST",
data: ko.toJSON(self.ChangeRequest()),
url: DomainUtil.baseUrl + "api/ChangeRequests/",
contentType: "application/json",
headers: { 'formUsage': formUsage }
},
function (updatedModel, status, request) {
var updateMessage = formUsage == 'execute' ? 'executed' : (formUsage == 'new' ? 'saved new' : transition == 'Delete Request' ? 'deleted' : 'updated');
var $msg = $("[id*='StatusMessage']");
$msg.html('Successfully ' + updateMessage + ' Change Request ' + updatedModel.id);
$msg.addClass('alertGo').show().fadeOut({ duration: 8000, easing: 'easeInQuint', complete: function () { $msg.removeClass('alertGo'); } });
if (formUsage == 'new') {
changeRequestViewModel.SetChangeRequest(new ChangeRequestModel());
CRHelper.SetEditors('new');
} else {
changeRequestViewModel.SetChangeRequest(new ChangeRequestModel(updatedModel));
CRHelper.SetEditors('edit');
}
if ((formUsage == 'editState' || formUsage == 'edit') && updatedModel.activeStateId === 8)
$('#approvedByItems').toggle();
if (formUsage === 'execute' || (formUsage === 'editState' && updatedModel.activeStateName == 'Approved')) {
$('#divExecuted').toggle();
$('#divChangeState').hide();
}
try {
$('#dtpDeadlineRequested').datepicker();
$('#dtpDeadlineRequested').datepicker('refresh');
} catch (e) {
$('#dtpDeadlineRequested').datepicker('destroy');
$('#dtpDeadlineRequested').datepicker();
}
if (transition == "Delete Request") {
$('.submitter').prop('disabled', true);
$('#divSubmitButtons #buttonSet').toggle();
$('#divSubmitButtons #returnLink').toggle();
$('#formFields').prop('disabled', true);
}
if (updatedModel.activeStateName == 'Executed' || updatedModel.activeStateName == 'Deleted' || updatedModel.activeStateName == 'Approved') {
$('#formFields').prop('disabled', true);
$('.editor').unbind('dblclick');
$('#divSubmitButtons #buttonSet').toggle();
$('#divSubmitButtons #returnLink').toggle();
}
},
function (request, status, error) {
//update message text
var $msg = $("[id*='StatusMessage']");
var updateMessage = formUsage == 'execute' ? 'executing' : (formUsage == 'new' ? 'saving' : 'updating');
$msg.html('Failure ' + updateMessage + ': ' + error);
$msg.addClass('alertStop').show().fadeOut({ duration: 8000, easing: 'easeInQuint', complete: function () { $msg.removeClass('alertStop'); } });
},
function () {
if (pwChooser)
pwChooser.selectedPW([]);
//hide spinny
}
);
utils.tokenizedAjax(ajax);
} else {
ko.validation.group(self.ChangeRequest()).showAllMessages();
var $msg = $("[id*='StatusMessage']");
$msg.html('Check your entries and try again')
.addClass('alertCaution')
.show()
.fadeOut({
duration: 2000,
easing: 'easeInQuint',
complete: function () {
$msg.removeClass('alertCaution');
}
});
}
}
And then here is where I declare the observables on the model - all pretty straightforward:
self.description = ko.observable(crData.description || '');
self.domain = ko.observable(crData.domain || '');
self.id = crData.id || 0;
self.impact = ko.observable(crData.impact || '');
self.includesPolicyWaiver = ko.observable(crData.includesPolicyWaiver || false);
self.justification = ko.observable(crData.justification || '');
self.priority = ko.observable(crData.priority || '');
self.scope = ko.observable(crData.scope || '');
self.securityClassification = ko.observable(crData.securityClassification || '');
self.title = ko.observable(crData.title || 'New Change Request');
self.validationProcess = ko.observable(crData.validationProcess || '');
I've triple-checked the code and there is nowhere else that the values behind these two form fields are being explicitly changed. This looks to me like a global-type value is getting toggled then not reset or something.
This is interesting: The only change I made was the order of the elements in the html. Doing the same test/submission, now the other fields that are in the 2nd and 4th position are showing the false positive. The ones that showed it originally validate as expected.

kendo grid inline edit dropdown will not expand on tab navigation

I'm having an issue with Kendo Grid in Angular where the custom drop down I've implemented will not open when tab navigating to that column. The built in text and number editor fields are editable on tab navigation but my custom drop down will not expand. I have to click on it to get the drop down effect.
My goal here is to allow the user to log an an entire row of data without having to take their hands off the keyboard.
My column is defined like so:
gridColumns.push({
field: currentField.FieldName.replace(/ /g, "_"),
title: currentField.FieldName,
editor: $scope.dropDownAttEditor,
template: function (dataItem) {
return $scope.dropDownTemplate(dataItem, currentField.FieldName);
}
});
My gridOptions are defined as follows:
$scope.gridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleInterval',
type: 'POST',
contentType: 'application/json'
},
update: {
url: appconfig.basePath + '/api/DrillHoleManager/DrillHoleIntervalUpdate',
type: 'POST',
contentType: 'application/json'
},
parameterMap: function (data, operation) {
if (operation === "read") {
data.DrillHoleId = $scope.entity.Id;
data.DrillHoleIntervalTypeId = $stateParams.ddhinttypeid;
// convert the parameters to a json object
return kendo.stringify(data);
}
if (operation === 'update') {
// build DrillHoleIntervalDto object with all ATT/CMT values to send back to server
var drillHoleInterval = { Id: data.Id, Name: data.Name, From: data.From, To: data.To };
drillHoleInterval.Attributes = [];
drillHoleInterval.Comments = [];
var attributeFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalAttribute });
$.each(attributeFields, function (idx, attributeField) {
drillHoleInterval.Attributes.push({
Id: attributeField.AttributeDto.Id,
LookupId: data[attributeField.FieldName.replace(/ /g, "_")]
});
});
var commentFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment });
$.each(commentFields, function (idx, commentField) {
drillHoleInterval.Comments.push({
Id: commentField.CommentDto.Id,
Value: ((data[commentField.FieldName.replace(/ /g, "_")] != "") ? data[commentField.FieldName.replace(/ /g, "_")] : null)
});
});
return kendo.stringify(drillHoleInterval);
}
// ALWAYS return options
return options;
}
},
schema: { model: { id : "Id" }},
serverPaging: false,
serverSorting: false,
serverFiltering: false
//,autoSync: true
}),
columns: gridColumns,
dataBound: onDataBound,
autoBind: false,
navigatable: true,
scrollable: false,
editable: true,
selectable: true,
edit: function (e) {
var grid = $("#ddhintgrid").data("kendoGrid");
//grid.clearSelection();
grid.select().removeClass('k-state-selected');
// select the row currently being edited
$('[data-uid=' + e.model.uid + ']').addClass('k-state-selected');
e.container[0].focus();
}
};
Here is a custom event to handle the 'Tab' keypress. The point of this is I want a new record automatically added to the grid if the user presses 'Tab' at the end of the last line:
$("#ddhintgrid").keydown(function (e) {
if (e.key == "Tab") {
var grid = $("#ddhintgrid").data("kendoGrid");
var data = grid.dataSource.data();
var selectedItem = grid.dataItem(grid.select());
var selectedIndex = null
if (selectedItem != null) {
selectedIndex = grid.select()[0].sectionRowIndex;
if (selectedIndex == data.length - 1) { // if the bottom record is selected
// We need to manually add a new record here so that the new row will automatically gain focus.
// Using $scope.addRecord() here will add the new row but cause the grid to lose focus.
var newRecord = { From: grid.dataSource.data()[selectedIndex].To };
var currentCmtFields = $.grep($scope.currentFields, function (e) { return e.DrillHoleTabFieldType == DrillHoleTabFieldTypeEnum.IntervalComment; });
$.each(currentCmtFields, function (idx, currentCmtField) {
newRecord[currentCmtField.FieldName.replace(/ /g, "_")] = null;
});
grid.dataSource.insert(data.length, newRecord);
// edit the new row
grid.editRow($("#ddhintgrid tr:eq(" + (data.length) + ")"));
}
}
}
});
Here is my template for the drop down column:
$scope.dropDownTemplate = function (dataItem, fieldName) {
var currentLookups = $.grep($scope.currentFields, function (e) { return e.FieldName == fieldName; })[0].AttributeDto.Lookups;
var selectedLookup = $.grep(currentLookups, function (e) { return e.Id == dataItem[fieldName.replace(/ /g, "_")]; })[0];
// With the custom dropdown editor when going from null to a value the entire lookup object (id, name) is placed in the
// dataItem[field_name] instead of just the id. We need to replace this object with just the id value and return the name of
// the lookup to the template.
if (typeof selectedLookup == 'undefined' && dataItem[fieldName.replace(/ /g, "_")] != null) {
selectedLookup = angular.copy(dataItem[fieldName.replace(/ /g, "_")]);
dataItem[fieldName.replace(/ /g, "_")] = selectedLookup.Id;
}
if (selectedLookup != null && selectedLookup != '') {
return selectedLookup.Name;
}
else {
return '';
}
};
And finally here is the custom editor for the drop down column:
$scope.dropDownAttEditor = function (container, options) {
var editor = $('<input k-data-text-field="\'Name\'" k-data-value-field="\'Id\'" k-data-source="ddlDataSource" data-bind="value:' + options.field + '"/>')
.appendTo(container).kendoDropDownList({
dataSource: $.grep($scope.currentFields, function (e) { return e.FieldName == options.field.replace(/_/g, ' '); })[0].AttributeDto.Lookups,
dataTextField: "Name",
dataValueField: "Id"
});
};
I know this is a lot to take in but if you have any questions just let me know.
My ultimate goal is that I want the user to be able to navigate the grid using the 'Tab' key and edit every field without having to use the mouse.

"TypeError: document is undefined" with jquery-1.10.2.js

I am creating a BackboneJS project. It works fine in Chrome and Safari, but in Firefox I get errors that stop my app from loading and I cannot work out why.
The error is in my jQuery file but it is obviously something in my app that is triggering it because the jQuery library is fine on its own.
It is throwing an error on the second line of the jQuery "createSafeFragment" method:
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
My main.js that runs the app:
Backbone.View.prototype.close = function () {
if (this.beforeClose) {
this.beforeClose();
}
this.remove();
this.unbind();
};
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
'login' : 'login',
'register' : 'register',
'rosters' : 'rosters',
'workplaces' : 'workplaces',
'groups' : 'groups',
'shifts' : 'shifts',
'logout' : 'logout'
},
content : '#content',
initialize: function () {
window.headerView = new HeaderView();
$('.header').html(window.headerView.render().el);
},
home: function () {
window.homePage = window.homePage ? window.homePage : new HomePageView();
app.showView( content, window.homePage);
window.headerView.select('home');
},
register: function () {
window.registerPage = window.registerPage ? window.registerPage : new RegisterPageView();
app.showView( content, window.registerPage);
window.headerView.select('register');
},
login: function() {
app.showView( content, new LoginPageView());
window.headerView.select('login');
},
rosters: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new RosterPageView());
window.headerView.select('rosters');
}
},
groups: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new GroupsPageView());
window.headerView.select('groups');
}
},
shifts: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new ShiftsPageView());
window.headerView.select('shifts');
}
},
workplaces: function () {
if(Utils.checkLoggedIn()){
app.showView( content, new WorkplacesPageView());
window.headerView.select('workplaces');
}
},
logout: function () {
window.headerView.toggleLogin(false);
this.login();
},
showView: function(selector, view) {
if (this.currentView)
this.currentView.close();
$(selector).html(view.render().el);
this.currentView = view;
return view;
}
});
Utils.loadTemplates(['HomePageView', 'HeaderView', 'LoginPageView', 'RegisterPageView',
'RostersPageView', 'GroupsPageView', 'ShiftsPageView', 'UserListView',
'GroupListView', 'ShiftListView', 'SearchedUserListView', 'SearchedGroupListView',
'GroupRosterView', 'RosterListView', 'WorkplacesPageView', 'WorkplaceListView',
'SearchedWorkplaceListView', 'RosterJoinListView', 'GroupUserListView',
'WorkplaceRosterView', 'WorkplaceUserListView', 'RosterShiftView'], function(){
app = new AppRouter();
Backbone.history.start();
});
And my Util.js:
Utils = {
//template stuff
templates: {},
loadTemplates: function(names, callback) {
var that = this;
var loadTemplate = function(index) {
var name = names[index];
$.get('tpl/' + name + '.html', function(data) {
that.templates[name] = data;
index++;
if (index < names.length) {
loadTemplate(index);
} else {
callback();
}
});
};
loadTemplate(0);
},
get: function(name) {
return this.templates[name];
},
//error stuff
showAlertMessage: function(message, type){
$('#error').html(message);
$('.alert').addClass(type);
$('.alert').show();
},
showErrors: function(errors) {
_.each(errors, function (error) {
var controlGroup = $('.' + error.name);
controlGroup.addClass('error');
controlGroup.find('.help-inline').text(error.message);
}, this);
},
hideErrors: function () {
$('.control-group').removeClass('error');
$('.help-inline').text('');
},
//validator stuff
validateModel: function(model, attrs){
Utils.hideErrors();
var valError = model.validate(attrs);
if(valError){
Utils.showErrors(valError);
return false;
}
return true;
},
//loading stuff
toggleLoading: function(toggle){
$('#loading').css('visibility', toggle ? 'visible' : 'hidden');
},
//login stuff
login: function(auth){
window.headerView.toggleLogin(true);
Backbone.history.navigate("", true);
},
checkLoggedIn: function(){
if(!window.userId){
window.headerView.toggleLogin(false);
Backbone.history.navigate("login", true);
return false;
}
return true;
},
//util methods
formatDate: function(date){
var formattedDate = '';
formattedDate += date.getFullYear() + '-';
formattedDate += date.getMonth()+1 + '-';
formattedDate += date.getDate();
return formattedDate;
},
formatDateForDisplay: function(date){
var formattedDate = '';
formattedDate += date.getDate() + '/';
formattedDate += date.getMonth()+1 + '/';
formattedDate += date.getFullYear() + ' - ';
formattedDate += ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
return formattedDate;
},
formatDateForGroup: function(date){
var formattedDate = '';
formattedDate += date.getDate() + '/';
formattedDate += date.getMonth()+1;
return formattedDate;
},
showPopup: function(id, buttons, title, content){
var popup = $(id);
popup.dialog({
modal: true,
title: title,
buttons: buttons
});
popup.find('#popupContent').html(content);
}
};
Someone please help me as this is driving me crazy! Firefox only...
I was also experiencing this problem. You can reproduce this error by doing:
$(window).append('bla');
Mine was cause by a combination of this:
click
and
function doIt(){
var newElm = $('<span>hi</span>');
$(this).append(newElm);
//now this === window, and not what I was expecting the a-element
}
This all happened because I expected the click would have been binded in a proper more-jquery-ish way to the a element. But someone decided to use 1999 code ;p. I expected for the method to be bound like this:
$("a").click(doIt);
In which case this would have been bound to the a-element and not to the window.
benhowdle89 figured out that I was appending to content when I should have been appending to this.content.
It is also a good idea to always use JSFiddle I have realised, so other people can see your problem on their own.
Thanks to benhowdle89!

Categories

Resources