How to restore/reuse json serialized objects in fabricjs? - json

I am trying to create a collaborative whiteboard with socket.io and fabric.js.
When a user draws something I send the path to other users as a JSON format:
canvas.on('path:created', function(e) {
canvas.remove(fabric.Path.fromObject(JSON.stringify(e.path)));
socket.emit('add path', e.path.toJSON());
});
How can I recreate this object on the canvas here?
socket.on('add path', function(path) {
canvas.add(path); // doesn't work
});

try to use fabric.util.enlinvenObjects
The purpouse of that function is to switch from object form to istance.
socket.on('add path', function(path) {
fabric.util.enlivenObjects([path], function(objects) {
objects.forEach(function(o) {
canvas.add(o);
});
});
});

For those calling this function in a TypeScript project...
In my case setting namespace to empty string ('') and explicitly typing the callback argument made the function work smoothly.
fabric.util.enlivenObjects(
action.payload.objects,
(enlivedObjects: fabric.Object[]) => {
canvas.add(...enlivedObjects);
canvas.renderAll();
},
'');

Related

How can we Read a local Json file in a html page without any server

I want to read a local Json file from a html page. But I am not able to read the local Json file in HTML page that work for chrome and IE.
Is there is any way to do it without using any web server.
Let's say you have,
index.html & sample.json in the same folder,
you can do this,
$http.get('sample.json').then(function(response) {
console.log(response);
});
of course you will need to run this from a controller, stand alone or in a directive, etc.
I found this solution on the web, i didn't try it but according to the comments it should work
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}``
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Create a JSON file named sample.json in a translation folder .Then in controllers use the below code to get the values present in JSON file
$http.get('translation/sample.json').success(function(response){
console.log(response);
});
or
$.getJSON('translation/sample.json', function(data){
console.log(data);
});

Ember.js Component properties data set by Ajax JSON

I have a Component that has an injected service, which makes an Ajax call. I can receive the JSON data successfully and can dump it into the console after the promise "THEN" returns.
Here's my component. I can see the dumped data, but how do I set the component properties with that JSON and have it accessible in the template? Also, why can't I use "this.get" in my function below?
import Ember from 'ember';
export default Ember.Component.extend({
attr_types: Ember.inject.service('svc-attrtypes'),
atype_list: [],
actions: {
getATypes: function() {
this.get('attr_types').getTypes().then(function(json){
console.log(json);
this.atype_list = json;
console.log(this.atype_list);
// below returns: TypeError: this.get is not a function
this.get('atype_list').pushObjects(json);
});
}
}
});
In my template I have this:
{{#each atype_list.alltypes as |a|}}
<li>{{a.attr_type}} - {{a.attr_type_desc}}</li>
{{/each}}
If I manually place my JSON into the atype_list it shows perfectly on the template. But if I try to set it after my Ajax returns, nothing shows, except for in the console output.
I appreciate any help. I am sure I a missing something simple. ( or more likely, I'm just going about this all wrong)
This changed with anonymous function passed to then. You have to save this or use es6 arrow function syntax.
import Ember from 'ember';
const { service } = Ember.inject;
export default Ember.Component.extend({
attrTypes: service('svc-attrtypes'),
atypeList: [],
actions: {
// es6 version
getATypes(){
this.get('attrTypes').getTypes().then(array => {
this.set('atypeList', array); //replaces original array
this.get('atypeList').pushObjects(array); // adds array's elements to the end
});
}
// es5 version
getATypes: function () {
var _this = this;
this.get('attrTypes').getTypes().then(function(array){
_this.set('atypeList', array);
}
}
}
});
You wrote that you are new to ember, so I added little more syntax sugar. Also check ember-cli if you don't know about that already.

IBM Worklight JSONStore - Add and get data

I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.

Persistent store load callback in ExtJS 4.1.1

I need a way to catch the JSON response every time my datastore has loaded. My first try was to use the autoLoad property but the callback fires only on first load :
autoLoad: {
callback: function (records, operation) {
// do something with operation.response.responseText
}
}
So, I have decided to extend the load method :
load: function (options) {
var callback = options && options.callback;
return this.callParent([Ext.apply(options || {}, {
callback: function (records, operation) {
// do something with operation.response.responseText
if (callback) {
return callback.apply(this, arguments);
}
}
})]);
}
It works, but I wonder if the framework already provides a more elegant solution.
You can add a load listener to the store and grab the current request from it's proxy when the load event is fired.
var myStore = Ext.create("Ext.data.store", {
...whatever here
listeners: {
load: function(store){
store.getProxy().activeRequest.options.operation.response.responseText;
}
}
});
Thats if you want the response text specifically. If you want the response as a JSON object, you can use store.getProxy().reader.rawData; which is a little simpler

JQuery return variable from JSON request

I have the following code to pull some data from an external source:
$(document).ready(function(){
$.getJSON('mydata.json',function(data) {
var ned = data.names.ned;
return(ned);
});
});
And In my JSON I have:
{
"names": {
"ned": "Eddard Stark",
"jon": "Jon Snow",
"tyrion": "Tyrion Lannister"
}
}
I want to know how can I use the variable 'ned' on another function. Also, I want further to set other variables like 'jon' and 'tyrion' to be able to use later, but I can't make them pass to another function.
The JSON callback must be done on page load to be able to proper use some of the app functions, that's why it's on document ready.
You can do that easily using jquery $.Deferred:
function getNed()
{
return $.getJSON('mydata.json').pipe(function(data) {
var ned = data.names.ned;
return ned;
});
}
getNed().done(function(ned) {
alert(ned);
});
A quick/easy way to do this would be to declare a global variable, then fill it with your data from the json call when you get it.
<script>
var myJsonData; //Make this a very unique name, as you may conflict with other variables in plugins and such.
$(document).ready(function(){
$.getJSON('mydata.json',function(data) {
myJsonData = data;
var ned = data.names.ned;
return(ned);
});
});
</script>
However, note that your getJSON call could take a long time, and you have to be diligent in checking that the myJsonData variable is not undefined before using it. Alternatively, you could call some sort of initialization function from the json callback.