How can i create a roll dice button? - javascript

I am trying to create a roll dice button for my code but I'm not quite sure how I can do this, since if I do create one then either it does not work how I want it too or my button does not function right.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" title="Default Styles"/>
<script>
var r_text = new Array ();
r_text[0] = "All leave are brown";
r_text[1] = "fafwfaf";
r_text[2] = "fakfjwkfkajwkfawjf";
r_text[3] = "cornflakes";
r_text[4] = "bannana";
r_text[5] = "Choclate";
r_text[6] = "lol";
var i = Math.floor(7*Math.random())
var videos = [
{
id: 1,
url: "https://www.youtube.com/embed/ngUMyF9D9SQ?autoplay=1",
text: r_text[i]
},
{
id: 2,
url: "https://www.youtube.com/embed/v=r-l_gVPVylM?autoplay=1",
text: r_text[i]
},
{
id: 3,
url: "https://www.youtube.com/embed/6ukTzRjXcR0?autoplay=1",
text: r_text[i]
},
{
id: 4,
url: "https://www.youtube.com/embed/n5BXMNCTu8I?autoplay=1",
text: r_text[i]
},
{
id: 5,
url: "https://www.youtube.com/embed/JtwVmnMNaEY?autoplay=1",
text: r_text[i]
},
{
id: 6,
url: "https://www.youtube.com/embed/lAMgRaHP8Q4?autoplay=1",
text: r_text[i]
}
];
window.onload = function() {
var playerDiv = document.getElementById("random_player");
var player = document.createElement("IFRAME");
var previousId = localStorage.getItem("previousId");
if (previousId) {
var previousIndex = videos.findIndex(v => v.id === parseInt(previousId));
videos.splice(previousIndex, 1);
}
var current = Math.floor(Math.random() * videos.length);
localStorage.setItem("previousId", videos[current].id);
localStorage.getItem("previousId");
var randomVideoUrl = videos[current].url;
player.setAttribute("width", "640");
player.setAttribute("height", "390");
player.setAttribute("src", randomVideoUrl);
playerDiv.appendChild(player);
var textContainer = document.getElementById("r_text");
setTimeout(() => {
textContainer.innerHTML = videos[current].text;
}, 3000)
};
</script>
</head>
<div id="random_player">
<div id="r_text">
</div>
</div>
</html>
I am expecting it to have nothing at first apart from the button and once the button is clicked then the video starts playing and then everything else starts to happen.

Try this https://codepen.io/dsb/pen/XWrQbxR
Explanation:
1) Add button to HTML
<button id="btn-roll">Roll</button>
2) Modify JS code
var r_text = [];
r_text[0] = "All leave are brown";
r_text[1] = "fafwfaf";
r_text[2] = "fakfjwkfkajwkfawjf";
r_text[3] = "cornflakes";
r_text[4] = "bannana";
r_text[5] = "Choclate";
r_text[6] = "lol";
var i = Math.floor(6 * Math.random())
var videos = [{
id: 1,
url: "https://www.youtube.com/embed/ngUMyF9D9SQ?autoplay=1",
text: r_text[1]
},
{
id: 2,
url: "https://www.youtube.com/embed/v=r-l_gVPVylM?autoplay=1",
text: r_text[2]
},
{
id: 3,
url: "https://www.youtube.com/embed/6ukTzRjXcR0?autoplay=1",
text: r_text[3]
},
{
id: 4,
url: "https://www.youtube.com/embed/n5BXMNCTu8I?autoplay=1",
text: r_text[4]
},
{
id: 5,
url: "https://www.youtube.com/embed/JtwVmnMNaEY?autoplay=1",
text: r_text[5]
},
{
id: 6,
url: "https://www.youtube.com/embed/lAMgRaHP8Q4?autoplay=1",
text: r_text[6]
}
];
window.onload = function() {
function rollVideo(numberRand) {
let playerDiv = document.getElementById("random_player");
if (document.querySelector("iframe") !== null) {
document.querySelector("iframe").remove();
}
let player = document.createElement("IFRAME");
let randomVideoUrl = videos[numberRand].url;
player.setAttribute("width", "640");
player.setAttribute("height", "390");
player.setAttribute("src", randomVideoUrl);
playerDiv.appendChild(player);
document.getElementById("r_text").innerHTML = "";
document.getElementById("r_text").innerHTML = videos[numberRand].text;
}
startRoll(i);
document.getElementById("btn-roll").addEventListener("click", startRoll);
function startRoll() {
let currentNumber = Math.floor(Math.random() * videos.length);
rollVideo(currentNumber);
}
};
There is no conditions about text variables and id of previous video so i minified the example.

As you can see i have added your code but nothing happens.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" title="Default Styles"/>
<script>
var r_text = new Array ();
r_text[0] = "All leave are brown";
r_text[1] = "fafwfaf";
r_text[2] = "fakfjwkfkajwkfawjf";
r_text[3] = "cornflakes";
r_text[4] = "bannana";
r_text[5] = "Choclate";
r_text[6] = "lol";
var i = Math.floor(7*Math.random())
var videos = [
{
id: 1,
url: "https://www.youtube.com/embed/ngUMyF9D9SQ?autoplay=1",
text: r_text[i]
},
{
id: 2,
url: "https://www.youtube.com/embed/v=r-l_gVPVylM?autoplay=1",
text: r_text[i]
},
{
id: 3,
url: "https://www.youtube.com/embed/6ukTzRjXcR0?autoplay=1",
text: r_text[i]
},
{
id: 4,
url: "https://www.youtube.com/embed/n5BXMNCTu8I?autoplay=1",
text: r_text[i]
},
{
id: 5,
url: "https://www.youtube.com/embed/JtwVmnMNaEY?autoplay=1",
text: r_text[i]
},
{
id: 6,
url: "https://www.youtube.com/embed/lAMgRaHP8Q4?autoplay=1",
text: r_text[i]
}
];
window.onload = function() {
function rollVideo(numberRand) {
var playerDiv = document.getElementById("random_player");
var player = document.createElement("IFRAME");
var previousId = localStorage.getItem("previousId");
if (previousId) {
var previousIndex = videos.findIndex(v => v.id === parseInt(previousId));
videos.splice(previousIndex, 1);
}}
var current = Math.floor(Math.random() * videos.length);
localStorage.setItem("previousId", videos[current].id);
localStorage.getItem("previousId");
var randomVideoUrl = videos[current].url;
player.setAttribute("width", "640");
player.setAttribute("height", "390");
player.setAttribute("src", randomVideoUrl);
playerDiv.appendChild(player);
var textContainer = document.getElementById("r_text");
setTimeout(() => {
textContainer.innerHTML = videos[current].text;
}, 3000)
};
document.getElementById("btn-roll").addEventListener("click", startRoll);
function startRoll() {
let currentNumber = Math.floor(Math.random() * videos.length);
rollVideo(currentNumber);
}
</script>
</head>
<div id="random_player">
<div id="r_text">
</div>
</div>
<button id="btn-roll">Roll</button>
</html>

Related

Push json data into nested array

Im trying to build this array:
[{
id: "1", name: labels,
periods: [
{id:"1_1", start: "2018-01-05", end: "2018-01-25"},
{id:"1_2", start: "2018-01-28", end: "2018-02-22"},
{id:"1_3", start: "2018-03-03", end: "2018-03-25"}
]
}];
I have this json data
labels = ["Workorder 1", ... , "Workorder 10"]
start = ["2019-01-01", ... ,"2019-01-25" ]
end= ["2019-01-10", ... ,"2019-01-25"]
this is how far I got:
var arr=[];
for ( var i=0; i<labels.length; i++){
newlab = labels[i];
newid = "id" + [i];
newstart = start[i];
newstop = end[i];
arr.push({ id:newid, name:newlab, start:newstart, end:newstop })
};
var data = {data:arr};
console.log(data);
which has this as output:
data = [
{id: "id0", name: "Workorder 1", start: "2019-01-01", end: "2019-01-10"},
....
{id: "id9", name: "Workorder 10", start: "2019-11-25", end: "2019-01-14"}
]
Thank you for any help
This will Work For you, Try this
var labels = ["Workorder 1", "Workorder 10"]
var start = ["2019-01-01", "2019-01-25"]
var end = ["2019-01-10", "2019-01-25"]
var obj = {}
var finalArray = []
for (var i = 1; i <= start.length; i++) {
var first = { id: i, name: 'labels' }
obj = { ...obj, ...first }
var periods = { id: i + '_' + i, name: labels[i - 1], start: start[i - 1], end: end[i - 1] }
if (obj.periods) {
obj.periods.push(periods)
} else {
obj.periods = [periods]
}
finalArray.push(obj)
}
var data = { data: finalArray };
console.log("finalOutput.............",data)
let labels="test_string",start = [],end=[],arr=[];
var arr=[],periods =[];
for ( var i=0; i<labels.length; i++){
obj = {};
obj.id= "1", obj.name= "labels"
newlab = labels[i];
newid = [i] + "_" + [i];
newstart = start[i];
newstop = end[i];
periods.push({ id:newid, name:newlab, start:newstart, end:newstop })
obj.periods = periods;
arr.push(obj)
};
let data = {data:arr};
console.log(data);

Why my cards are not randomly placed?

I am writing a memory card game. Each time when I refresh the page, the cards are supposed to place in a random position but it turns out that they remain in the same position.
here is the code :
var cardsArray = [{
'name': 'ball',
'img': '../img/ball.png',
},
{
'name': 'building',
'img': '../img/building.png',
},
{
'name': 'fan',
'img': '../img/fan.png',
},
{
'name': 'fish',
'img': '../img/fish.png',
},
{
'name': 'fishball',
'img': '../img/fishball.png',
},
{
'name': 'flower',
'img': '../img/flower.png',
},
{
'name': 'hill',
'img': '../img/hill.png',
},
{
'name': 'orange',
'img': '../img/orange.png',
},
{
'name': 'boo',
'img': '../img/boo.png',
},
{
'name': 'shoe',
'img': '../img/shoe.png',
},
];
var firstGuess = '';
var secondGuess = '';
var count = 0;
var previousTarget = null;
var delay = 1200;
var moves;
var matched;
var score;
var game = document.getElementById('game');
var grid = document.createElement('section');
const gameGrid = cardsArray
.concat(cardsArray)
.sort(function() {
0.5 - Math.random()
});
function startGame() {
grid.setAttribute('class', 'grid');
game.appendChild(grid);
moves = 0;
score = 0;
matched = 0;
document.getElementById("moves").innerHTML = moves;
document.getElementById("score").innerHTML = score;
gameGrid.forEach(function(item) {
const {
name,
img
} = item;
const card = document.createElement('div');
card.classList.add('card');
card.dataset.name = name;
const front = document.createElement('div');
front.classList.add('front');
const back = document.createElement('div');
back.classList.add('back');
back.style.backgroundImage = `url(${img})`;
grid.appendChild(card);
card.appendChild(front);
card.appendChild(back);
});
}
Sorry, I know it might be a bit long, but I guess the problem might be here:
const gameGrid = cardsArray
.concat(cardsArray)
.sort(function() {
0.5 - Math.random()
});
Did I do something wrong here? How can i fix it?
You're not actually returning the random value to sort on.
const gameGrid = cardsArray
.concat(cardsArray)
.sort(function() {
return 0.5 - Math.random()
});

Change javascript object structure

I have an object format like this :
var groupArray=[{
name: "blabla bla",
code: "1"
},
{
name: "blabla bla2",
code: "12"
},
{
name: "blabla bla3",
code: "123"
}];
I would transform it to this structure
var groupArray=[{
type: "Grp",
code: "1"
},
{
type: "Grp",
code: "12"
},
{
type: "Grp",
code: "123"
}];
Here's a JSFiddle demo
function update() {
var array = "";
var arrayreturn = this.getPrice(this.groupArray);
alert(arrayreturn)
arrayreturn.map(function(elm) {
this.array += elm + " ";
});
document.getElementById("objectTransform").innerHTML = array;
}
var groupArray = [{
name: "blabla bla",
code: "1"
},
{
name: "blabla bla2",
code: "12"
},
{
name: "blabla bla3",
code: "123"
}
];
function getPrice(array) {
var newObject = [{
typeObject: "",
code: ""
}];
for (var i = 0; i < array.length; i++) {
newObject[i].typeObject = "group";
newObject[i].code = array[i].code
}
return newObject
}
My problem is when I click on the button to change the structure of my object I got no result
You're trying to access to an index that doesn't exist.
Just push the new elements to the new array.
function update() {
var array = "";
var arrayreturn = this.getPrice(this.groupArray);
console.log(arrayreturn)
arrayreturn.map(function(elm) {
this.array += elm + " ";
});
document.getElementById("objectTransform").innerHTML = array;
}
var groupArray = [{ name: "blabla bla", code: "1" }, { name: "blabla bla2", code: "12" }, { name: "blabla bla3", code: "123" }];
function getPrice(array) {
var newObject = [];
for (var i = 0; i < array.length; i++) {
newObject.push({
type: 'Grp',
code: array[i].code
});
}
return newObject
}
<button onClick="update();">Click me</button>
<div id="objectTransform">PRICE HERE</div>
An alternative using the function map
function update() {
var array = "";
var arrayreturn = this.getPrice(this.groupArray);
console.log(arrayreturn)
arrayreturn.map(function(elm) {
this.array += elm + " ";
});
document.getElementById("objectTransform").innerHTML = array;
}
var groupArray = [{ name: "blabla bla", code: "1" }, { name: "blabla bla2", code: "12" }, { name: "blabla bla3", code: "123" }];
function getPrice(array) {
return array.map(function(o) {
return { type: 'Grp', code: o.code }
});
}
<button onClick="update();">Click me</button>
<div id="objectTransform">PRICE HERE</div>

JavaScript - How to make matching game cards stay flipped over after click

I found this matching game on codepen.io that I am using in corporation with a trivia spinner - thanks #Malky.kid - The idea is once they get to the matching game they have 10 clicks to match as many as they can but the cards MUST stay flipped over.
This is for a project and the odds of winning has to do with chance not skill.
(function(){
var Memory = {
init: function(cards){
this.$game = $(".game");
this.$modal = $(".modal");
this.$overlay = $(".modal-overlay");
this.$restartButton = $("button.restart");
this.cardsArray = $.merge(cards, cards);
this.shuffleCards(this.cardsArray);
this.setup();
},
shuffleCards: function(cardsArray){
this.$cards = $(this.shuffle(this.cardsArray));
},
setup: function(){
this.html = this.buildHTML();
this.$game.html(this.html);
this.$memoryCards = $(".card");
this.binding();
this.paused = false;
this.guess = null;
},
binding: function(){
this.$memoryCards.on("click", this.cardClicked);
this.$restartButton.on("click", $.proxy(this.reset, this));
},
// kinda messy but hey
cardClicked: function(){
var _ = Memory;
var $card = $(this);
if(!_.paused && !$card.find(".inside").hasClass("matched") && !$card.find(".inside").hasClass("picked")){
$card.find(".inside").addClass("picked");
if(!_.guess){
_.guess = $(this).attr("data-id");
} else if(_.guess == $(this).attr("data-id") && !$(this).hasClass("picked")){
$(".picked").addClass("matched");
_.guess = null;
} else {
_.guess = null;
_.paused = true;
setTimeout(function(){
$(".picked").removeClass("picked");
Memory.paused = false;
}, 600);
}
if($(".matched").length == $(".card").length){
_.win();
}
}
},
win: function(){
this.paused = true;
setTimeout(function(){
Memory.showModal();
Memory.$game.fadeOut();
}, 1000);
},
showModal: function(){
this.$overlay.show();
this.$modal.fadeIn("slow");
},
hideModal: function(){
this.$overlay.hide();
this.$modal.hide();
},
reset: function(){
this.hideModal();
this.shuffleCards(this.cardsArray);
this.setup();
this.$game.show("slow");
},
// Fisher--Yates Algorithm -- https://bost.ocks.org/mike/shuffle/
shuffle: function(array){
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
},
buildHTML: function(){
var frag = '';
this.$cards.each(function(k, v){
frag += '<div class="card" data-id="'+ v.id +'"><div class="inside">\
<div class="front"><img src="'+ v.img +'"\
alt="'+ v.name +'" /></div>\
<div class="back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/codepen-logo.png"\
alt="Codepen" /></div></div>\
</div>';
});
return frag;
}
};
var cards = [
{
name: "php",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/php-logo_1.png",
id: 1,
},
{
name: "css3",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/css3-logo.png",
id: 2
},
{
name: "html5",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/html5-logo.png",
id: 3
},
{
name: "jquery",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/jquery-logo.png",
id: 4
},
{
name: "javascript",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/js-logo.png",
id: 5
},
{
name: "node",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/nodejs-logo.png",
id: 6
},
{
name: "photoshop",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/photoshop-logo.png",
id: 7
},
{
name: "python",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/python-logo.png",
id: 8
},
{
name: "rails",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/rails-logo.png",
id: 9
},
{
name: "sass",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/sass-logo.png",
id: 10
},
{
name: "sublime",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/sublime-logo.png",
id: 11
},
{
name: "wordpress",
img: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/wordpress-logo.png",
id: 12
},
];
Memory.init(cards);
})();
see game here
The only difference to this is that the cards stay flipped over - if they match cards they should still show that they are matched - it highlights green for a second. The cards flip back over after you select two cards ONLY if they do not match. If they do match they stay facing up but I need it always facing up. Thanks

TypeError: module.PosModel is undefined

I inherited on the point_of_sale models.js file in order to add a model. This by following code:
openerp.dewieuw = function(instance, local) { //module is instance.point_of_sale
var module = instance.point_of_sale;
var QWeb = instance.web.qweb;
var _t = instance.web._t;
var round_di = instance.web.round_decimals;
var round_pr = instance.web.round_precision
alert(instance.point_of_sale)
alert(module)
module.PosModel = module.PosModel.extend({
models: [
{
model: 'res.users',
fields: ['name','company_id'],
ids: function(self){ return [self.session.uid]; },
loaded: function(self,users){ self.user = users[0]; },
},{
model: 'res.company',
fields: [ 'currency_id', 'email', 'website', 'company_registry', 'vat', 'name', 'phone', 'partner_id' , 'country_id', 'tax_calculation_rounding_method'],
ids: function(self){ return [self.user.company_id[0]] },
loaded: function(self,companies){ self.company = companies[0]; },
},{
model: 'decimal.precision',
fields: ['name','digits'],
loaded: function(self,dps){
self.dp = {};
for (var i = 0; i < dps.length; i++) {
self.dp[dps[i].name] = dps[i].digits;
}
},
},{
model: 'product.uom',
fields: [],
domain: null,
loaded: function(self,units){
self.units = units;
var units_by_id = {};
for(var i = 0, len = units.length; i < len; i++){
units_by_id[units[i].id] = units[i];
units[i].groupable = ( units[i].category_id[0] === 1 );
units[i].is_unit = ( units[i].id === 1 );
}
self.units_by_id = units_by_id;
}
},{
model: 'res.users',
fields: ['name','ean13'],
domain: null,
loaded: function(self,users){ self.users = users; },
},{
model: 'res.partner',
fields: ['name','street','city','state_id','country_id','vat','phone','zip','mobile','email','ean13','write_date','nieuwsbrief','klantgroep','lang'],
domain: [['customer','=',true]],
loaded: function(self,partners){
self.partners = partners;
self.db.add_partners(partners);
},
},{
model: 'res.lang',
fields: ['name', 'code'],
loaded: function(self,langs){
self.langs = langs;
},
},{
model: 'klantgroep',
fields: ['name'],
loaded: function(self,klantgroepen){
self.klantgroepen = klantgroepen;
},
},{
model: 'res.country',
fields: ['name'],
loaded: function(self,countries){
self.countries = countries;
self.company.country = null;
for (var i = 0; i < countries.length; i++) {
if (countries[i].id === self.company.country_id[0]){
self.company.country = countries[i];
}
}
},
},{
model: 'account.tax',
fields: ['name','amount', 'price_include', 'include_base_amount', 'type', 'child_ids', 'child_depend', 'include_base_amount'],
domain: null,
loaded: function(self, taxes){
self.taxes = taxes;
self.taxes_by_id = {};
_.each(taxes, function(tax){
self.taxes_by_id[tax.id] = tax;
});
_.each(self.taxes_by_id, function(tax) {
tax.child_taxes = {};
_.each(tax.child_ids, function(child_tax_id) {
tax.child_taxes[child_tax_id] = self.taxes_by_id[child_tax_id];
});
});
},
},{
model: 'pos.session',
fields: ['id', 'journal_ids','name','user_id','config_id','start_at','stop_at','sequence_number','login_number'],
domain: function(self){ return [['state','=','opened'],['user_id','=',self.session.uid]]; },
loaded: function(self,pos_sessions){
self.pos_session = pos_sessions[0];
var orders = self.db.get_orders();
for (var i = 0; i < orders.length; i++) {
self.pos_session.sequence_number = Math.max(self.pos_session.sequence_number, orders[i].data.sequence_number+1);
}
},
},{
model: 'pos.config',
fields: [],
domain: function(self){ return [['id','=', self.pos_session.config_id[0]]]; },
loaded: function(self,configs){
self.config = configs[0];
self.config.use_proxy = self.config.iface_payment_terminal ||
self.config.iface_electronic_scale ||
self.config.iface_print_via_proxy ||
self.config.iface_scan_via_proxy ||
self.config.iface_cashdrawer;
self.barcode_reader.add_barcode_patterns({
'product': self.config.barcode_product,
'cashier': self.config.barcode_cashier,
'client': self.config.barcode_customer,
'weight': self.config.barcode_weight,
'discount': self.config.barcode_discount,
'price': self.config.barcode_price,
});
if (self.config.company_id[0] !== self.user.company_id[0]) {
throw new Error(_t("Error: The Point of Sale User must belong to the same company as the Point of Sale. You are probably trying to load the point of sale as an administrator in a multi-company setup, with the administrator account set to the wrong company."));
}
},
},{
model: 'stock.location',
fields: [],
ids: function(self){ return [self.config.stock_location_id[0]]; },
loaded: function(self, locations){ self.shop = locations[0]; },
},{
model: 'product.pricelist',
fields: ['currency_id'],
ids: function(self){ return [self.config.pricelist_id[0]]; },
loaded: function(self, pricelists){ self.pricelist = pricelists[0]; },
},{
model: 'res.currency',
fields: ['symbol','position','rounding','accuracy'],
ids: function(self){ return [self.pricelist.currency_id[0]]; },
loaded: function(self, currencies){
self.currency = currencies[0];
if (self.currency.rounding > 0) {
self.currency.decimals = Math.ceil(Math.log(1.0 / self.currency.rounding) / Math.log(10));
} else {
self.currency.decimals = 0;
}
},
},{
model: 'product.packaging',
fields: ['ean','product_tmpl_id'],
domain: null,
loaded: function(self, packagings){
self.db.add_packagings(packagings);
},
},{
model: 'pos.category',
fields: ['id','name','parent_id','child_id','image'],
domain: null,
loaded: function(self, categories){
self.db.add_categories(categories);
},
},{
model: 'product.product',
fields: ['display_name', 'list_price','price','pos_categ_id', 'taxes_id', 'ean13', 'default_code',
'to_weight', 'uom_id', 'uos_id', 'uos_coeff', 'mes_type', 'description_sale', 'description',
'product_tmpl_id'],
domain: [['sale_ok','=',true],['available_in_pos','=',true]],
context: function(self){ return { pricelist: self.pricelist.id, display_default_code: false }; },
loaded: function(self, products){
self.db.add_products(products);
},
},{
model: 'account.bank.statement',
fields: ['account_id','currency','journal_id','state','name','user_id','pos_session_id'],
domain: function(self){ return [['state', '=', 'open'],['pos_session_id', '=', self.pos_session.id]]; },
loaded: function(self, bankstatements, tmp){
self.bankstatements = bankstatements;
tmp.journals = [];
_.each(bankstatements,function(statement){
tmp.journals.push(statement.journal_id[0]);
});
},
},{
model: 'account.journal',
fields: [],
domain: function(self,tmp){ return [['id','in',tmp.journals]]; },
loaded: function(self, journals){
self.journals = journals;
// associate the bank statements with their journals.
var bankstatements = self.bankstatements;
for(var i = 0, ilen = bankstatements.length; i < ilen; i++){
for(var j = 0, jlen = journals.length; j < jlen; j++){
if(bankstatements[i].journal_id[0] === journals[j].id){
bankstatements[i].journal = journals[j];
}
}
}
self.cashregisters = bankstatements;
},
},{
label: 'fonts',
loaded: function(self){
var fonts_loaded = new $.Deferred();
// Waiting for fonts to be loaded to prevent receipt printing
// from printing empty receipt while loading Inconsolata
// ( The font used for the receipt )
waitForWebfonts(['Lato','Inconsolata'], function(){
fonts_loaded.resolve();
});
// The JS used to detect font loading is not 100% robust, so
// do not wait more than 5sec
setTimeout(function(){
fonts_loaded.resolve();
},5000);
return fonts_loaded;
},
},{
label: 'pictures',
loaded: function(self){
self.company_logo = new Image();
var logo_loaded = new $.Deferred();
self.company_logo.onload = function(){
var img = self.company_logo;
var ratio = 1;
var targetwidth = 300;
var maxheight = 150;
if( img.width !== targetwidth ){
ratio = targetwidth / img.width;
}
if( img.height * ratio > maxheight ){
ratio = maxheight / img.height;
}
var width = Math.floor(img.width * ratio);
var height = Math.floor(img.height * ratio);
var c = document.createElement('canvas');
c.width = width;
c.height = height
var ctx = c.getContext('2d');
ctx.drawImage(self.company_logo,0,0, width, height);
self.company_logo_base64 = c.toDataURL();
logo_loaded.resolve();
};
self.company_logo.onerror = function(){
logo_loaded.reject();
};
self.company_logo.crossOrigin = "anonymous";
self.company_logo.src = '/web/binary/company_logo' +'?_'+Math.random();
return logo_loaded;
},
},
],
});
module.ClientListScreenWidget = module.ClientListScreenWidget.extend({
// what happens when we save the changes on the client edit form -> we fetch the fields, sanitize them,
// send them to the backend for update, and call saved_client_details() when the server tells us the
// save was successfull.
save_client_details: function(partner) {
var self = this;
var fields = {}
this.$('.client-details-contents .detail').each(function(idx,el){
fields[el.name] = el.value;
if(el.name=='nieuwsbrief'){
fields[el.name] = el.checked;
}
});
if (!fields.name) {
this.pos_widget.screen_selector.show_popup('error',{
message: _t('A Customer Name Is Required'),
});
return;
}
if (this.uploaded_picture) {
fields.image = this.uploaded_picture;
}
fields.id = partner.id || false;
fields.country_id = fields.country_id || false;
fields.ean13 = fields.ean13 ? this.pos.barcode_reader.sanitize_ean(fields.ean13) : false;
new instance.web.Model('res.partner').call('create_from_ui',[fields]).then(function(partner_id){
self.saved_client_details(partner_id);
},function(err,event){
event.preventDefault();
self.pos_widget.screen_selector.show_popup('error',{
'message':_t('Error: Could not Save Changes'),
'comment':_t('Your Internet connection is probably down.'),
});
});
},
});
}
This worked like a charm. But now I wanted to inherit on the website_sale.js file so I added some test code to this file. And now I always get this error:
TypeError: module.PosModel is undefined
I deleted this test code, but still the error occurs. Any ideas? I also placed my whole module back to a backup were everything worked fine, but I'm still getting this error.
Have you added point_of_sale dependency in website_sale module openerp.py file ?
If not, please add it and try again.

Categories

Resources