How can we clone an object in Polymer?
Example
this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();
this.colorsDesc[0].color = 'blue'; // Both will be blue doing this
I can do it in these many functionalities What is the most efficient way to deep clone an object in JavaScript? but I wonder if there is a way in Polymer to do that?
Angular does it https://docs.angularjs.org/api/ng/function/angular.copy
You can try the following hack:
this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
I have had the same question here, where I have finally also found and posted an answer.
Short version:
newElement = element.cloneNode(true);
for(var i in element.properties) {
newElement[i] = element[i]
}
To clone a utility via Polymer
Full implementation:
(function(callBackFn) {
Polymer({
//Component Name
is: 'my-cloner',
properties: {
//Declare a published property
cloneableObject: { //Placeholder for Object to be cloned
reflectToAttribute: true,
type: Object,
notify: true
}
},
attached: function() {
//Hide if this component got attached
this.hidden = true;
},
getClone: function(incomingcloneableObject) { //Will be called to get the Clone
this.cloneableObject = this.cloneableObject || incomingcloneableObject;
switch (typeof this.cloneableObject) {
case "undefined":
return null;
break;
case "object":
var localClone = this.cloneNode();
return (localClone.cloneableObject);
break;
case "boolean":
return new Boolean(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject ? true : false);
break;
case "number": //NaN is taken care of
return new Number(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject * 1);
break;
case "string":
return new String(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject + '');
break;
default:
return null;
}
}
});
//adding Util into window
callBackFn();
})(function() {
window.cloneUtil = document.createElement('my-cloner');
});
//To use this util
//window.cloneUtil.getClone();
Related
I am making a simple note taking app to learn node and ES6. I have 3 modules - App, NotesManager and Note. I am importing the Note class into the NotesManager and am trying to instantiate it in its addNote function. The problem is that even though the import is correct, it turns out to be undefined inside the class definition. A simpler solution would be to just instantiate the NotesManager class and add the Note class to its constructor however, I want to have NotesManager as a static utility class.
Here is my code.
Note.js
class Note {
constructor(title, body) {
this.title = title;
this.body = body;
}
}
module.exports = Note;
NotesManager.js
const note = require("./Note");
console.log("Note: ", note); //shows correctly
class NotesManager {
constructor() {}
static addNote(title, body) {
const note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(note);
}
static getNote(title) {
if (title) {
console.log(`Getting Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static removeNote(title) {
if (title) {
console.log(`Removing Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static getAll() {
//console.log("Getting all notes ", NotesManager.notes, note);
}
}
NotesManager.notes = []; //Want notes to be a static variable
module.exports.NotesManager = NotesManager;
App.js
console.log("Starting App");
const fs = require("fs"),
_ = require("lodash"),
yargs = require("yargs"),
{ NotesManager } = require("./NotesManager");
console.log(NotesManager.getAll()); //works
const command = process.argv[2],
argv = yargs.argv;
console.log(argv);
switch (command) {
case "add":
const title = argv.title || "No title given";
const body = argv.body || "";
NotesManager.addNote(title, body); //Fails here
break;
case "list":
NotesManager.getAll();
break;
case "remove":
NotesManager.removeNote(argv.title);
break;
case "read":
NotesManager.getNote(argv.title);
break;
default:
notes.getAll();
break;
}
Is it possible for me to create a strict utility class which I can use without instantiating like in Java? Pretty new here and have tried searching for it without any luck. Thank you for your help.
When you do this:
const note = new note(title, body);
you redefine note shadowing the original note from the outer scope. You need to pick a different variable name.
Something like this should work better:
static addNote(title, body) {
const some_note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(some_note);
}
On the time of page loaded get_switch() function which globally created on app.js page will be call then return a method. i want to execute these return methods.
demo.js
const return_functions = get_switch('BTC');
function get_btc()
{
console.log('btc');
}
function get_bch()
{
console.log('bch');
}
app.js
global.get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
return 'get_btc()';
break;
case 'BCH':
return 'get_bth()';
break;
default:
console.log('default');
}
}
As shown in example above i have passed BTC in get_switch. and that function return us get_btc() function. so i want to call get_btc function on same time.
If this is not possible in this way so please guide me with your idea and suggest me how can i do this.
demo.js
var obj = {
get_btc: function get_btc() {
console.log('btc');
},
get_bth: function get_bth() {
console.log('get_bth');
}
}
const return_functions = get_switch('BTC');
if (return_functions) {
obj[return_functions]();
}
app.js
global.get_switch = function (coin_name) {
switch (coin_name) {
case 'BTC':
return 'get_btc';
break;
case 'BCH':
return 'get_bth';
break;
default:
console.log('default');
}
}
var get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
get_btc();
break;
case 'BCH':
get_bth();
break;
default:
console.log('default');
}
}
get_switch('BTC');
function get_btc() {
console.log('btc');
}
function get_bch() {
console.log('bch');
}
I am new to Phaserjs, trying to create basic drag-drop style game.
I have created the game and add arcade physics (this.game.physics.arcade.enable(this.orange_outline);)
Currently overlap happen as soon as the edges collide.
I want to detect that my code should trigger when 50% overlap happen. is it possible in phaserjs?
var GameState = {
init:function(){
this.physics.startSystem(Phaser.Physics.ARCADE);
},
create: function () {
this.background = this.game.add.sprite(0, 0, 'background');
this.overlapHappen = false;
this.orange_outline = this.game.add.sprite(459,199,'orange_outline');
this.orange_outline.frame = 2;
this.orange_outline.anchor.setTo(.5);
this.orange_outline.customParams = {myName:'orange_outline',questionImg:'orange'};
this.orange_inner = this.game.add.sprite(150,197,'orange_inner');
this.orange_inner.anchor.setTo(.5);
this.orange_inner.customParams = {myName:'orange_inner',questionImg:'orange',targetKey:this.orange_outline,targetImg:'orange_outline'};
this.orange_inner.frame = 1;
this.orange_inner.inputEnabled = true;
this.orange_inner.input.enableDrag();
this.orange_inner.input.pixelPerfectOver = true;
this.orange_inner.events.onDragStart.add(this.onDragStart,this);
// this.game.physics.enable(this.orange_inner,Phaser.Physics.ARCADE);
this.game.physics.arcade.enable(this.orange_inner);
this.game.physics.arcade.enable(this.orange_outline);
this.orange_inner.events.onDragStop.add(this.onDragStop,this);
},
update: function () {
//this.orange.animations.play('orange_one',1)
},
onDragStart:function(sprite,pointer){
//console.log(sprite.key + " dragged")
},
onDragStop:function(sprite,pointer){
var endSprite = sprite.customParams.targetKey;
//console.log(sprite.customParams);
this.stopDrag(sprite,endSprite)
},
stopDrag:function(currentSprite,endSprite){
if (!this.game.physics.arcade.overlap(currentSprite, endSprite, function() {
var currentSpriteTarget = currentSprite.customParams.targetImg;
var endSpriteName = endSprite.customParams.myName;
if(currentSpriteTarget === endSpriteName){
currentSprite.input.draggable = false;
currentSprite.position.copyFrom(endSprite.position);
currentSprite.anchor.setTo(endSprite.anchor.x, endSprite.anchor.y);
}
console.log(currentSpriteTarget,endSpriteName);
})) {
//currentSprite.position.copyFrom(currentSprite.originalPosition);
console.log('you')
}
}
}
In stopDrag() I am detecting overlap.
You can try to get the amount of horizontal and vertical overlap amount and check if it satisfies a certain threshold. This can be done in additional overlap function callback, that is called processCallback in documentation. As an example:
if (!this.game.physics.arcade.overlap(currentSprite, endSprite, function() {
//your callback !
},function() {
if (this.game.physics.arcade.getOverlapX(currentSprite, endSprite) > currentSprite.width / 2
&& this.game.physics.arcade.getOverlapY(currentSprite, endSprite) > currentSprite.height / 2) {
//Overlaping !
return true;
} else {
//as if no overlap occured
return false;
}
},this) {
//
}
Another way to do this (other than what Hamdi Douss offers) is to resize your body to only take up 50% of the area. This will automatically ensure that collisions/overlap don't occur unless the reduced bodies touch each other.
To view your current body, use Phaser's debug methods
this.game.debug.body(someSprite, 'rgba(255,0,0,0.5)');
I have been trying to get the per pixel drag and drop feature working using images with fabric.js like in example on their website: http://fabricjs.com/per-pixel-drag-drop/. I would like the object to be detected when a non transparent part is moused over but if I set perpixeltargetfind to true nothing is detected. I have tried for a while now and even copying the example verbatim while using my own images has not worked. Would really appreciate some help figuring out what I am doing wrong if anyone has experience using this. Thanks.
Here is a link to a js fiddle I have been using: http://jsfiddle.net/ahalbleib/bdofdbqg/
and the code:
var canvas =this.__canvas = new fabric.Canvas('c1',{hoverCursor: 'pointer',
selection: false});
var urls=['https://dl.dropboxusercontent.com/s/ix6mvv49wnx226a/Central-Richmon_clipped_rev_1.png?dl=0' ,
'https://dl.dropboxusercontent.com/s/jjp2l0kgdw8iitb/Laurel-Heights.png?dl=0',
'https://dl.dropboxusercontent.com/s/wdk02w40z1466g5/LoneMountain.png?dl=0',
'https://dl.dropboxusercontent.com/s/t6tnptndu2k22xr/OuterRichmond.png?dl=0',
'https://dl.dropboxusercontent.com/s/tv4rhwjc0nw35iz/Presidio-Heights.png?dl=0' ,
'https://dl.dropboxusercontent.com/s/ttbf390w2vdx4id/Inner-richmond.png?dl=0'];
for (var i=0; i<urls.length; i++){
fabric.Image.fromURL( urls[i], function(img){
img.perPixelTargetFind = true;
img.targetFindTolerance = 4;
img.hasControls = img.hasBorders = false;
canvas.add(img);
});
}
canvas.findTarget = (function (originalFn) {
return function () {
var target = originalFn.apply(this, arguments);
if (target) {
if (this._hoveredTarget !== target) {
canvas.fire('object:over', { target: target });
if (this._hoveredTarget) {
canvas.fire('object:out', { target: this._hoveredTarget });
}
this._hoveredTarget = target;
}
}
else if (this._hoveredTarget) {
canvas.fire('object:out', { target: this._hoveredTarget });
this._hoveredTarget = null;
}
return target;
};
})(canvas.findTarget);
};
init();
That is because you don't take images from your own server and you'll get a Security error about tainted canvas. You need to set crossOrigin: 'Anonymous' to images. I made you a jsFiddle
I'm using chrome.storage in an extension and would like to avoid triggering runtime errors due to exceeding one of the documented throttles for either the sync or local stores. (things like QUOTA_BYTES, QUOTA_BYTES_PER_ITEM)
My first choice would be to intercept these errors prior to a runtime error being generated; alternatively I could track usage on the extension side and try to avoid triggering them.
This feels like an issue that someone must have addressed, but I can't seem to find any solutions - any suggestions appreciated.
Here's a sample of the solution I'm going with (using Angular, so there are promises in here), although having to regex the chrome.runtime.lastError value is pretty ugly IMO:
var service = {
error: function(lastError) {
if((lastError) && (lastError.message)) {
var errorString = lastError.message;
if(/QUOTA_BYTES/.test(errorString)) {
return true;
} else if(/QUOTA_BYTES_PER_ITEM/.test(errorString)) {
return true;
} else if(/MAX_ITEMS/.test(errorString)) {
return true;
} else if(/MAX_WRITE_OPERATIONS_PER_HOUR/.test(errorString)) {
return true;
} else if(/MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE/.test(errorString)) {
return true;
}
return false;
} else {
return false;
}
},
write: function(key, value) {
var deferred = $q.defer();
var data = {};
data[key] = value;
chrome.storage.sync.set(data, function() {
if(service.error(chrome.runtime.lastError)) {
deferred.reject('Write operation failed: '
+ chrome.runtime.lastError.message);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
};
return service;