I'm working on odoo9,I have a date field in my model, I want to enable only Mondays in its calendar, I found Jquery solutions on google and applied to my date field but could not get the desired result. Instead I get two calendars , second one is shown when I continue to press left click on my date field.See second Image.
Second image.
This is my Jquery code:
$('.o_datepicker_input').datepicker({
beforeShowDay: function (date)
{
return [(date.getDay() == 1), ""];
},
});
try this
$(".week").datepicker("option", {
beforeShowDay: function (date)
{
return [date.getDay() == 1, ''];
}
});
var weekOptions = { "changeMonth": false, "changeYear": false, "stepMonths": 0,
beforeShowDay: function (date) {
return [date.getDay() == 1, ''];
}
};
$(function () {
$(".week").datepicker("option", weekOptions);
});
Here is the answer. Little bit tricky.
odoo.define('automation.saturday_datepicker', function (require) {
"use strict";
var core = require('web.core');
var formats = require('web.formats');
var time = require('web.time');
var Widget = require('web.Widget');
var _t = core._t;
`enter code here`var DateWidget = Widget.extend({
template: "web.datepicker",
type_of_date: "date",
events: {
'dp.change': 'change_datetime',
'dp.show': 'set_datetime_default',
'change .o_datepicker_input': 'change_datetime',
},
init: function(parent, options) {
this._super.apply(this, arguments);
var l10n = _t.database.parameters;
this.name = parent.name;
this.options = _.defaults(options || {}, {
pickTime: this.type_of_date === 'datetime',
useSeconds: this.type_of_date === 'datetime',
startDate: moment({ y: 1900 }),
endDate: moment().add(200, "y"),
calendarWeeks: true,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down'
},
language : moment.locale(),
format : time.strftime_to_moment_format((this.type_of_date === 'datetime')? (l10n.date_format + ' ' + l10n.time_format) : l10n.date_format),
daysOfWeekDisabled: [0, 1,2,3,4,5],
});
},
start: function() {
this.$input = this.$('input.o_datepicker_input');
this.$el.datetimepicker(this.options);
this.picker = this.$el.data('DateTimePicker');
this.set_readonly(false);
this.set_value(false);
},
set_value: function(value) {
this.set({'value': value});
this.$input.val((value)? this.format_client(value) : '');
this.picker.setValue(this.format_client(value));
},
get_value: function() {
return this.get('value');
},
set_value_from_ui: function() {
var value = this.$input.val() || false;
this.set_value(this.parse_client(value));
},
set_readonly: function(readonly) {
this.readonly = readonly;
this.$input.prop('readonly', this.readonly);
},
is_valid: function() {
var value = this.$input.val();
if(value === "") {
return true;
} else {
try {
this.parse_client(value);
return true;
} catch(e) {
return false;
}
}
},
parse_client: function(v) {
return formats.parse_value(v, {"widget": this.type_of_date});
},
format_client: function(v) {
return formats.format_value(v, {"widget": this.type_of_date});
},
set_datetime_default: function() {
//when opening datetimepicker the date and time by default should be the one from
//the input field if any or the current day otherwise
var value = moment().second(0);
if(this.$input.val().length !== 0 && this.is_valid()) {
value = this.$input.val();
}
// temporarily set pickTime to true to bypass datetimepicker hiding on setValue
// see https://github.com/Eonasdan/bootstrap-datetimepicker/issues/603
var saved_picktime = this.picker.options.pickTime;
this.picker.options.pickTime = true;
this.picker.setValue(value);
this.picker.options.pickTime = saved_picktime;
},
change_datetime: function(e) {
if(this.is_valid()) {
this.set_value_from_ui();
this.trigger("datetime_changed");
}
},
commit_value: function() {
this.change_datetime();
},
destroy: function() {
this.picker.destroy();
this._super.apply(this, arguments);
},
});
var DateTimeWidget = DateWidget.extend({
type_of_date: "datetime"
});
return {
DateWidget: DateWidget,
DateTimeWidget: DateTimeWidget,
};
});
odoo.define('web.form_widgets_custom', function (require) {
"use strict";
var core = require('web.core');
var common = require('web.form_common');
var formats = require('web.formats');
var automation_saturday_date_picker = require('automation.saturday_datepicker')
var _t = core._t;
var QWeb = core.qweb;
var FieldDatetime = core.form_widget_registry.get('datetime')
var FieldDate = FieldDatetime.extend({
template: "FieldDate",
build_widget: function() {
return new automation_saturday_date_picker.DateWidget(this);
}
});
core.form_widget_registry
.add('saturday_date_widget', FieldDate)
});
And finally give widget="saturday_date_widget" to model's field in xml.
Related
I'm seeking a solution for the toastr.js "error" that causes the webpage, if scrolled down, to jump up again when a new toastr is displayed
GitHub page containing the script
I've tried to change the top to auto, but that wasn't an accepted parameter, because nothing showed up then.
Isn't there any way to make it appear where the mouse is at the moment?
.toast-top-center {
top: 12px;
margin: 0 auto;
left: 43%;
}
this has the calling code:
<p><span style="font-family:'Roboto','One Open Sans', 'Helvetica Neue', Helvetica, sans-serif;color:rgb(253,253,255); font-size:16px ">
xxxxxxxxxxxxx
</span></p>
This is the function code:
<script type='text/javascript'> function playclip() {
toastr.options = {
"debug": false,
"positionClass": "toast-top-center",
"onclick": null,
"fadeIn": 800,
"fadeOut": 1000,
"timeOut": 5000,
"extendedTimeOut": 1000
}
toastr["error"]("This link is pointing to a page that hasn't been written yet,</ br> sorry for the inconvenience?"); } </script>
And this is the script itself:
/*
* Toastr
* Copyright 2012-2015
* Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* ARIA Support: Greta Krafsig
*
* Project: https://github.com/CodeSeven/toastr
*/
/* global define */
(function (define) {
define(['jquery'], function ($) {
return (function () {
var $container;
var listener;
var toastId = 0;
var toastType = {
error: 'error',
info: 'info',
success: 'success',
warning: 'warning'
};
var toastr = {
clear: clear,
remove: remove,
error: error,
getContainer: getContainer,
info: info,
options: {},
subscribe: subscribe,
success: success,
version: '2.1.3',
warning: warning
};
var previousToast;
return toastr;
////////////////
function error(message, title, optionsOverride) {
return notify({
type: toastType.error,
iconClass: getOptions().iconClasses.error,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function getContainer(options, create) {
if (!options) { options = getOptions(); }
$container = $('#' + options.containerId);
if ($container.length) {
return $container;
}
if (create) {
$container = createContainer(options);
}
return $container;
}
function info(message, title, optionsOverride) {
return notify({
type: toastType.info,
iconClass: getOptions().iconClasses.info,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function subscribe(callback) {
listener = callback;
}
function success(message, title, optionsOverride) {
return notify({
type: toastType.success,
iconClass: getOptions().iconClasses.success,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function warning(message, title, optionsOverride) {
return notify({
type: toastType.warning,
iconClass: getOptions().iconClasses.warning,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function clear($toastElement, clearOptions) {
var options = getOptions();
if (!$container) { getContainer(options); }
if (!clearToast($toastElement, options, clearOptions)) {
clearContainer(options);
}
}
function remove($toastElement) {
var options = getOptions();
if (!$container) { getContainer(options); }
if ($toastElement && $(':focus', $toastElement).length === 0) {
removeToast($toastElement);
return;
}
if ($container.children().length) {
$container.remove();
}
}
// internal functions
function clearContainer (options) {
var toastsToClear = $container.children();
for (var i = toastsToClear.length - 1; i >= 0; i--) {
clearToast($(toastsToClear[i]), options);
}
}
function clearToast ($toastElement, options, clearOptions) {
var force = clearOptions && clearOptions.force ? clearOptions.force : false;
if ($toastElement && (force || $(':focus', $toastElement).length === 0)) {
$toastElement[options.hideMethod]({
duration: options.hideDuration,
easing: options.hideEasing,
complete: function () { removeToast($toastElement); }
});
return true;
}
return false;
}
function createContainer(options) {
$container = $('<div/>')
.attr('id', options.containerId)
.addClass(options.positionClass);
$container.appendTo($(options.target));
return $container;
}
function getDefaults() {
return {
tapToDismiss: true,
toastClass: 'toast',
containerId: 'toast-container',
debug: false,
showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
showDuration: 300,
showEasing: 'swing', //swing and linear are built into jQuery
onShown: undefined,
hideMethod: 'fadeOut',
hideDuration: 1000,
hideEasing: 'swing',
onHidden: undefined,
closeMethod: false,
closeDuration: false,
closeEasing: false,
closeOnHover: true,
extendedTimeOut: 1000,
iconClasses: {
error: 'toast-error',
info: 'toast-info',
success: 'toast-success',
warning: 'toast-warning'
},
iconClass: 'toast-info',
positionClass: 'toast-top-right',
timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
titleClass: 'toast-title',
messageClass: 'toast-message',
escapeHtml: false,
target: 'body',
closeHtml: '<button type="button">×</button>',
closeClass: 'toast-close-button',
newestOnTop: true,
preventDuplicates: false,
progressBar: false,
progressClass: 'toast-progress',
rtl: false
};
}
function publish(args) {
if (!listener) { return; }
listener(args);
}
function notify(map) {
var options = getOptions();
var iconClass = map.iconClass || options.iconClass;
if (typeof (map.optionsOverride) !== 'undefined') {
options = $.extend(options, map.optionsOverride);
iconClass = map.optionsOverride.iconClass || iconClass;
}
if (shouldExit(options, map)) { return; }
toastId++;
$container = getContainer(options, true);
var intervalId = null;
var $toastElement = $('<div/>');
var $titleElement = $('<div/>');
var $messageElement = $('<div/>');
var $progressElement = $('<div/>');
var $closeElement = $(options.closeHtml);
var progressBar = {
intervalId: null,
hideEta: null,
maxHideTime: null
};
var response = {
toastId: toastId,
state: 'visible',
startTime: new Date(),
options: options,
map: map
};
personalizeToast();
displayToast();
handleEvents();
publish(response);
if (options.debug && console) {
console.log(response);
}
return $toastElement;
function escapeHtml(source) {
if (source == null) {
source = '';
}
return source
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function personalizeToast() {
setIcon();
setTitle();
setMessage();
setCloseButton();
setProgressBar();
setRTL();
setSequence();
setAria();
}
function setAria() {
var ariaValue = '';
switch (map.iconClass) {
case 'toast-success':
case 'toast-info':
ariaValue = 'polite';
break;
default:
ariaValue = 'assertive';
}
$toastElement.attr('aria-live', ariaValue);
}
function handleEvents() {
if (options.closeOnHover) {
$toastElement.hover(stickAround, delayedHideToast);
}
if (!options.onclick && options.tapToDismiss) {
$toastElement.click(hideToast);
}
if (options.closeButton && $closeElement) {
$closeElement.click(function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
event.cancelBubble = true;
}
if (options.onCloseClick) {
options.onCloseClick(event);
}
hideToast(true);
});
}
if (options.onclick) {
$toastElement.click(function (event) {
options.onclick(event);
hideToast();
});
}
}
function displayToast() {
$toastElement.hide();
$toastElement[options.showMethod](
{duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
);
if (options.timeOut > 0) {
intervalId = setTimeout(hideToast, options.timeOut);
progressBar.maxHideTime = parseFloat(options.timeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
if (options.progressBar) {
progressBar.intervalId = setInterval(updateProgress, 10);
}
}
}
function setIcon() {
if (map.iconClass) {
$toastElement.addClass(options.toastClass).addClass(iconClass);
}
}
function setSequence() {
if (options.newestOnTop) {
$container.prepend($toastElement);
} else {
$container.append($toastElement);
}
}
function setTitle() {
if (map.title) {
var suffix = map.title;
if (options.escapeHtml) {
suffix = escapeHtml(map.title);
}
$titleElement.append(suffix).addClass(options.titleClass);
$toastElement.append($titleElement);
}
}
function setMessage() {
if (map.message) {
var suffix = map.message;
if (options.escapeHtml) {
suffix = escapeHtml(map.message);
}
$messageElement.append(suffix).addClass(options.messageClass);
$toastElement.append($messageElement);
}
}
function setCloseButton() {
if (options.closeButton) {
$closeElement.addClass(options.closeClass).attr('role', 'button');
$toastElement.prepend($closeElement);
}
}
function setProgressBar() {
if (options.progressBar) {
$progressElement.addClass(options.progressClass);
$toastElement.prepend($progressElement);
}
}
function setRTL() {
if (options.rtl) {
$toastElement.addClass('rtl');
}
}
function shouldExit(options, map) {
if (options.preventDuplicates) {
if (map.message === previousToast) {
return true;
} else {
previousToast = map.message;
}
}
return false;
}
function hideToast(override) {
var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod;
var duration = override && options.closeDuration !== false ?
options.closeDuration : options.hideDuration;
var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing;
if ($(':focus', $toastElement).length && !override) {
return;
}
clearTimeout(progressBar.intervalId);
return $toastElement[method]({
duration: duration,
easing: easing,
complete: function () {
removeToast($toastElement);
clearTimeout(intervalId);
if (options.onHidden && response.state !== 'hidden') {
options.onHidden();
}
response.state = 'hidden';
response.endTime = new Date();
publish(response);
}
});
}
function delayedHideToast() {
if (options.timeOut > 0 || options.extendedTimeOut > 0) {
intervalId = setTimeout(hideToast, options.extendedTimeOut);
progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
}
}
function stickAround() {
clearTimeout(intervalId);
progressBar.hideEta = 0;
$toastElement.stop(true, true)[options.showMethod](
{duration: options.showDuration, easing: options.showEasing}
);
}
function updateProgress() {
var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
$progressElement.width(percentage + '%');
}
}
function getOptions() {
return $.extend({}, getDefaults(), toastr.options);
}
function removeToast($toastElement) {
if (!$container) { $container = getContainer(); }
if ($toastElement.is(':visible')) {
return;
}
$toastElement.remove();
$toastElement = null;
if ($container.children().length === 0) {
$container.remove();
previousToast = undefined;
}
}
})();
});
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
if (typeof module !== 'undefined' && module.exports) { //Node
module.exports = factory(require('jquery'));
} else {
window.toastr = factory(window.jQuery);
}
}));
Change your code to be like this:
<a href="#" style="color: rgb(255,0,0,0)" onclick="playclip(); return false;" >xxxxxxxxxxxxx </a>
However, I would reconsider using this type of javascript invokation. Take a look at this "javascript:void(0);" vs "return false" vs "preventDefault()"
How can I make a To-Do List, and at 5 elements checked to show a button?
I have already done the To-Do list (in HTML and JavaScript - my code below ), but I don't know how can I write a code to show a button at 5 elements checked.
My JSFiddle:
https://jsfiddle.net/sd355qxp
My code (in HTML and JavaScript) :
<html>
<head>
<link rel="stylesheet" href="tomo.css">
<title>TOMO</title>
</head>
<body>
<h1>TOMO</h1>
<center>
<div id="todo-app">
<label class="todo-label" for="new-todo">What do you have to do today?</label>
<input type="text" id="new-todo" class="todo-input" placeholder="english homework">
<ul id="todo-list" class="count-this"></ul>
<div id="todo-stats"></div>
</div>
</center>
<script type="text/x-template" id="todo-item-template">
<div class="todo-view">
<input type="checkbox" class="todo-checkbox" {checked}>
<span class="todo-content" tabindex="0">{text}</span>
</div>
<div class="todo-edit">
<input type="text" class="todo-input" value="{text}">
</div>
<a href="#" class="todo-remove" title="Remove this task">
<span class="todo-remove-icon"></span>
</a>
</script>
<script type="text/x-template" id="todo-stats-template">
<span class="todo-count">
<span class="todo-remaining">{numRemaining}</span>
<span class="todo-remaining-label">{remainingLabel}</span> left.
</span>
<a href="#" class="todo-clear">
Clear <span class="todo-done">{numDone}</span>
completed <span class="todo-done-label">{doneLabel}</span>
</a>
</script>
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event-focus', 'json', 'model', 'model-list', 'view', function (Y) {
var TodoAppView, TodoList, TodoModel, TodoView;
TodoModel = Y.TodoModel = Y.Base.create('todoModel', Y.Model, [], {
sync: LocalStorageSync('todo'),
toggleDone: function () {
this.set('done', !this.get('done')).save();
}
}, {
ATTRS: {
done: {value: false},
text: {value: ''}
}
});
TodoList = Y.TodoList = Y.Base.create('todoList', Y.ModelList, [], {
model: TodoModel,
sync: LocalStorageSync('todo'),
done: function () {
return this.filter(function (model) {
return model.get('done');
});
},
remaining: function () {
return this.filter(function (model) {
return !model.get('done');
});
}
});
TodoAppView = Y.TodoAppView = Y.Base.create('todoAppView', Y.View, [], {
events: {
'#new-todo': {keypress: 'createTodo'},
'.todo-clear': {click: 'clearDone'},
'.todo-item': {
mouseover: 'hoverOn',
mouseout : 'hoverOff'
}
},
template: Y.one('#todo-stats-template').getHTML(),
initializer: function () {
var list = this.todoList = new TodoList();
list.after('add', this.add, this);
list.after('reset', this.reset, this);
list.after(['add', 'reset', 'remove', 'todoModel:doneChange'],
this.render, this);
list.load();
},
render: function () {
var todoList = this.todoList,
stats = this.get('container').one('#todo-stats'),
numRemaining, numDone;
if (todoList.isEmpty()) {
stats.empty();
return this;
}
numDone = todoList.done().length;
numRemaining = todoList.remaining().length;
stats.setHTML(Y.Lang.sub(this.template, {
numDone : numDone,
numRemaining : numRemaining,
doneLabel : numDone === 1 ? 'task' : 'tasks',
remainingLabel: numRemaining === 1 ? 'task' : 'tasks'
}));
if (!numDone) {
stats.one('.todo-clear').remove();
}
return this;
},
add: function (e) {
var view = new TodoView({model: e.model});
this.get('container').one('#todo-list').append(
view.render().get('container')
);
},
clearDone: function (e) {
var done = this.todoList.done();
e.preventDefault();
this.todoList.remove(done, {silent: true});
Y.Array.each(done, function (todo) {
todo.destroy({remove: true});
});
this.render();
},
createTodo: function (e) {
var inputNode, value;
if (e.keyCode === 13) { // enter key
inputNode = this.get('inputNode');
value = Y.Lang.trim(inputNode.get('value'));
if (!value) { return; }
this.todoList.create({text: value});
inputNode.set('value', '');
}
},
hoverOff: function (e) {
e.currentTarget.removeClass('todo-hover');
},
hoverOn: function (e) {
e.currentTarget.addClass('todo-hover');
},
reset: function (e) {
var fragment = Y.one(Y.config.doc.createDocumentFragment());
Y.Array.each(e.models, function (model) {
var view = new TodoView({model: model});
fragment.append(view.render().get('container'));
});
this.get('container').one('#todo-list').setHTML(fragment);
}
}, {
ATTRS: {
container: {
valueFn: function () {
return '#todo-app';
}
},
inputNode: {
valueFn: function () {
return Y.one('#new-todo');
}
}
}
});
TodoView = Y.TodoView = Y.Base.create('todoView', Y.View, [], {
containerTemplate: '<li class="todo-item"/>',
events: {
'.todo-checkbox': {click: 'toggleDone'},
'.todo-content': {
click: 'edit',
focus: 'edit'
},
'.todo-input' : {
blur : 'save',
keypress: 'enter'
},
'.todo-remove': {click: 'remove'}
},
template: Y.one('#todo-item-template').getHTML(),
initializer: function () {
var model = this.get('model');
model.after('change', this.render, this);
model.after('destroy', function () {
this.destroy({remove: true});
}, this);
},
render: function () {
var container = this.get('container'),
model = this.get('model'),
done = model.get('done');
container.setHTML(Y.Lang.sub(this.template, {
checked: done ? 'checked' : '',
text : model.getAsHTML('text')
}));
container[done ? 'addClass' : 'removeClass']('todo-done');
this.set('inputNode', container.one('.todo-input'));
return this;
},
edit: function () {
this.get('container').addClass('editing');
this.get('inputNode').focus();
},
enter: function (e) {
if (e.keyCode === 13) {
Y.one('#new-todo').focus();
}
},
remove: function (e) {
e.preventDefault();
this.constructor.superclass.remove.call(this);
this.get('model').destroy({'delete': true});
},
save: function () {
this.get('container').removeClass('editing');
this.get('model').set('text', this.get('inputNode').get('value')).save();
},
toggleDone: function () {
this.get('model').toggleDone();
}
});
function LocalStorageSync(key) {
var localStorage;
if (!key) {
Y.error('No storage key specified.');
}
if (Y.config.win.localStorage) {
localStorage = Y.config.win.localStorage;
}
var data = Y.JSON.parse((localStorage && localStorage.getItem(key)) || '{}');
function destroy(id) {
var modelHash;
if ((modelHash = data[id])) {
delete data[id];
save();
}
return modelHash;
}
function generateId() {
var id = '',
i = 4;
while (i--) {
id += (((1 + Math.random()) * 0x10000) | 0)
.toString(16).substring(1);
}
return id;
}
function get(id) {
return id ? data[id] : Y.Object.values(data);
}
function save() {
localStorage && localStorage.setItem(key, Y.JSON.stringify(data));
}
function set(model) {
var hash = model.toJSON(),
idAttribute = model.idAttribute;
if (!Y.Lang.isValue(hash[idAttribute])) {
hash[idAttribute] = generateId();
}
data[hash[idAttribute]] = hash;
save();
return hash;
}
return function (action, options, callback) {
var isModel = Y.Model && this instanceof Y.Model;
switch (action) {
case 'create': // intentional fallthru
case 'update':
callback(null, set(this));
return;
case 'read':
callback(null, get(isModel && this.get('id')));
return;
case 'delete':
callback(null, destroy(isModel && this.get('id')));
return;
}
};
}
new TodoAppView();
});
</script>
</body>
</html>
Can you use jQuery?
$(".todo-checkbox").change(function(){
if($(".todo-checkbox:checked").length > 4){
$("#yourButton").show();
}
});
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!
I've been all over the related questions but couldn't find an answer to my problem.
http://s1308.hizliresim.com/1d/5/r50lw.png
When I click "Kredi Yükle" a popup should appear but nothing happens and i get these console errors.
What should i do?
In related js file :
CreditLoadingAmrEditor = Class.create({
SELECTION_WINDOW : "wndCreditLoadingHelper",
BUTTON_OK : "btnLoadCreditOk",
BUTTON_CANCEL : "btnLoadCreditCancel",
CREDIT_AMOUNT : "fld_credit_amount",
initialize: function(owner) {
this.owner = owner;
this.browser = owner.browser;
this.buttonOk = $(this.BUTTON_OK);
this.buttonCancel = $(this.BUTTON_CANCEL);
this.selectionWindow = this.initializeHelper(this.SELECTION_WINDOW);
var containers = $$("div[id='loadingCreditContainer']");
if (containers && containers.size() > 0) {
this.container = containers[0];
this.editorManager = new EditorManager("loadingCreditContainer");
this.creditAmount = $(this.CREDIT_AMOUNT).instance;
}
this.browser.addToolClickListener(this);
this.buttonOk.observe(iconstants.KEY_CLICK, this.okClick.bindAsEventListener(this));
this.buttonCancel.observe(iconstants.KEY_CLICK, this.closeClick.bindAsEventListener(this));
},
initializeHelper: function(windowName) {
var result = $(windowName);
if (result){
result.remove();
document.body.appendChild(result);
}
return result;
},
toolClick: function(browser, toolType) {
if (toolType == browser.TOOL_LOAD_CREDIT) {
this.show();
}
return false;
},
show: function(callback) {
this.callback = callback;
FSystem.registerWindow(this.selectionWindow, true, true);
},
hide: function() {
FSystem.unregisterWindow(this.selectionWindow);
},
okClick: function() {
if (this.creditAmount.getValue() >= 0) {
this.hide();
this.requestForLoadingCredit();
} else {
window.alert(localize("value_must_greater_than_0"));
}
},
closeClick: function() {
this.hide();
},
requestForLoadingCredit: function() {
FSystem.startWait();
new Ajax.Request(
iconstants.URL_CREDIT_LOADING_AMR,
{
method : iconstants.METHOD_POST,
parameters : {mid:this.browser.getSelectedId(),ca:this.creditAmount.getValue()},
onComplete : this.responseForDeviceReading.bind(this),
onException : null
});
},
responseForDeviceReading: function(transport) {
FSystem.stopWait();
var JSON = transport.responseText.evalJSON();
if (JSON.status == iconstants.AJAX_STATUS_OK){
//if (confirm(JSON.message)) {
window.open(JSON.url, '_newtab', 'width=1280,height=800');
//}
} else {
alert(JSON.message);
}
}
});
Such type of error occur when your object is not initialized. You are trying to access a method of such object which is not initialized. Please check your object initialization.
here is my code
var s;
var AddEvent = {
settings : {
saveButton : $('#uploadfiles1'),
cancelSpeech : $('.cancelSpeech'),
datePicker : $(".datepicker"),
eventName : $('input[name=eventname]'),
eventDate : $('input[name=eventdate]')
},
init:function(s){
s = this.settings;
this.BindEvents();
$('.Wallpapers').addClass('active');
$('input, textarea').placeholder();
},
BindEvents:function(){
this.CancelButton();
this.DatePicker();
// this.SaveButton();
$('input[type=text],textarea').on('keyup change',function(){
AddEvent.FieldsCheck();
});
},
CancelButton: function()
{
s.cancelSpeech.on('click',function(){
var referrer = document.referrer;
window.location = referrer;
});
},
DatePicker :function()
{
s.datePicker.datepicker({
//defaultDate: +7,
showOtherMonths: true,
autoSize: true,
//appendText: '(dd-mm-yyyy)',
dateFormat: 'dd/mm/yy'
});
},
SaveButton: function()
{
this.ClearFields();
},
FieldsCheck: function()
{
alert(s.eventName.attr('name'));
if(s.eventName.val()!='' && s.eventDate.val() !='' && $('textarea').val()!='')
{
s.saveButton.removeAttr('disabled').removeClass('disabled');
}
else
s.saveButton.attr('disabled','disabled').addClass('disabled');
},
ClearFields:function()
{
$('input,textarea').val('');
this.FieldsCheck();
}
};
$(function(){
AddEvent.init(s);
});
i am impletenting this example http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/
but each time when i type in my input field at this line i get undefined in alert
alert(s.eventName.attr('name'));
please tell me what am i doing wrong i tried to search but couldnt find anything usefull.
edit: here i created a little jsfiddle i am getting
TypeError: this.settings is undefined
[Break On This Error]
console.log(this.settings.eventName.attr('id'));
thanks
Your problem is here :
var s;
AddEvent.init(s);
There is no way after this to have s defined.
A solution would be to simply not pass s (and no declare it in the arguments of the function) :
init:function(s){
s = this.settings;
...
AddEvent.init();
But that lets a variable polluting the global namespace.
If you want your settings to be accessed from all your functions, you could embed in in a closure :
var AddEvent = (function(){
var settings;
return {
init:function(){
settings = {
saveButton : $('#uploadfiles1'),
cancelSpeech : $('.cancelSpeech'),
datePicker : $(".datepicker"),
eventName : $('input[name=eventname]'),
eventDate : $('input[name=eventdate]')
};
this.BindEvents();
$('.Wallpapers').addClass('active');
$('input, textarea').placeholder();
},
BindEvents:function(){
this.CancelButton();
this.DatePicker();
// this.SaveButton();
$('input[type=text],textarea').on('keyup change',function(){
AddEvent.FieldsCheck();
});
},
CancelButton: function()
{
settings.cancelSpeech.on('click',function(){
var referrer = document.referrer;
window.location = referrer;
});
},
DatePicker :function()
{
settings.datePicker.datepicker({
//defaultDate: +7,
showOtherMonths: true,
autoSize: true,
//appendText: '(dd-mm-yyyy)',
dateFormat: 'dd/mm/yy'
});
},
SaveButton: function()
{
this.ClearFields();
},
FieldsCheck: function()
{
alert(settings.eventName.attr('name'));
if(settings.eventName.val()!='' && settings.eventDate.val() !='' && $('textarea').val()!='')
{
settings.saveButton.removeAttr('disabled').removeClass('disabled');
}
else
settings.saveButton.attr('disabled','disabled').addClass('disabled');
},
ClearFields:function()
{
$('input,textarea').val('');
this.FieldsCheck();
}
}
})();
$(function(){
AddEvent.init();
});