I have a JSON that used by other parts in application a few times.
To avoid unneeded calls, I want to fetch it ones, and than only use it
where it needs.
the issue is, that JSON cantains a different sections for different parts,
thats why I need to use root property.
What I need:
- Proxy that will fetch it ones (One for all)
- Reader for each part, 'cause they use different root
- Store for different parts
Proxy:
var myProxy = new Ext.data.proxy.Ajax({
url: "static/data/myData.json"
});
var operation = new Ext.data.Operation({
action: "read"
});
myProxy.read(operation);
Some Part:
// try to create custom reader with appropriate root
var reader = new Ext.data.reader.Json({
root: "table1"
});
// set reader to proxy
myProxy.setReader(reader);
// create store
Ext.create("Ext.data.Store", {
storeId: "MyStore",
model: "MyModel",
autoLoad: true
});
// set proxy to store
Ext.data.StoreManager.lookup("MyStore").setProxy(proxy);
Of course, this doesn't work. How I have to do it?
You'd be better off using a AJAX fetch to get the JSON, caching it in some variable and then using your store's loadData method to fill each store as needed. loadData lets you manually add records without going to the remote data source. That'll give you tighter control without having to deal with the proxies; just the readers and stores.
Related
I've been developing a diagramming tool, I used JSPlumb.
I made shapes using css and connections are made through JSplumb.
I need to save the diagram as json or xml format. But I am having a hard time.
For example, this is the function for saving the diagram
$(function save() {
//$("#editor").resizable("destroy");
Objs = [];
$('#editor').each(function(){
Objs.push({id:$(this).attr('id'), html:$(this).html(), left:$(this).css('left'), top:$(this).css('top'), width:$(this).css('width'), height:$(this).css('height')});
});
console.log(Objs);
});
Also, I've been trying the stringify for getting the data and parse for loading but I still can't figure it out.
Is there a way that I can save jsplumb to json or xml?
Whenever a connection is established, "connection" event is triggered. You need to store the connection endpoints details in that triggered function so that you can retrieve them later.
First make sure that you have set proper id for your endpoints. You can manually set at time of endpoint creation as:
var e0 = jsPlumb.addEndpoint("div1",{uuid:"div1_ep1"}), // You can also set uuid based on element it is placed on
e1 = jsPlumb.addEndpoint("div2",{uuid:"div2_ep1"});
Now bind the connection event where you will store the established connections info:
var uuid, index=0; // Array to store the endpoint sets.
jsPlumb.bind("connection", function(ci) {
var eps = ci.connection.endpoints;
console.log(eps[0].getUuid() +"->"+ eps[1].getUuid()); // store this information in 2d-Array or any other format you wish
uuid[index][0]=eps[0].getUuid(); // source endpoint id
uuid[index++][1]=eps[1].getUuid(); // target endpoint id
}
});
You can convert the array information to JSON format and store it. On restoring, connect the endpoints based on uuid. code:
jsPlumb.connect({ uuids:["div1_ep1","div2_ep1"] });
Here is the jsFiddle for making connections based on endpoints.
NOTE: The above code is only for restoring the connection and endpoints information after you have restored the div's css. You can store the css properties of all div's by using the same method which you wrote in your question.
I just recently tied this and its working
function createJSON(){
var data = new Object();
$("input[class = process]").each(function(){
data[$(this).attr("name")] = $(this).val();
jsonString = JSON.stringify(data);
});
console.log(jsonString);
}
I have 2 entity managers:
var mgr1 = new breeze.EntityManager('api/app');
var mgr2 = new breeze.EntityManager('api/app');
Right now I am getting the metadata for each one separately, although the metadata is exactly the same. I am calling the fetch method explicitly to control the timing of when the metadata is loaded.
mgr1.fetchMetadata();
mgr2.fetchMetadata();
I've read that I can share the metadata between the 2 managers but I have not found an example. From what I've read, I think I can specify the metadata in the constructor of the 2nd manager that references the 1st manager's metadata, but not sure what that would look like. So my code would look something like this:
var mgr1 = new breeze.EntityManager('api/app');
mgr1.fetchMetadata();
var mgr2 = new breeze.EntityManager({ serviceName: 'api/app', metadata: WHAT_GOES_HERE});
I know I will also have to sequnece this with promises so the 2nd manager isn't constructed before the 1st managers has it's metadata loaded.
Am I on the right path with this? My goal is to eliminate the extra bandwidth to load the metadata for the 2nd manager. thanks
You don't actually have to fetch the metadata to share the same MetadataStore. The following two statements are a pretty crisp approach:
var em1 = new breeze.EntityManager('api/app');
var em2 = em1.createEmptyCopy();
I'm not trying to be clever. My point is that a MetadataStore, which is a container of metadata, is available immediately after EntityManager creation and is well defined prior to holding any metadata whatsoever.
The createEmptyCopy() method "clones" the manager without copying its entity cache contents. The copied attributes include the manager's MetadataStore and its DataService.
Because the managers share the same MetadataStore, fetching metadata with either manager will do the trick.
Check out the Breeze API documentation for EntityManager and MetadataStore.
I have never used breeze.js before, but from what I gather from the documentation (http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html), something like this should work:
var mgr1 = new breeze.EntityManager('api/app');
mgr1.fetchMetadata();
var mgr2 = new breeze.EntityManager({
serviceName: 'api/app',
metadataStore: mgr1.metadataStore
});
Of course mgr2 should be set up after the mgr1.fetchMetadata promise is fulfilled, as you already say in your question.
I’m trying to understand how and where to use data after a fetch using Backbone.js but I’m a little confused.
I’ll explain the situation.
I have an app that, on the startup, get some data from a server. Three different kind of data.
Let’s suppose Airplanes, Bikes, Cars.
To do that, I’ve inserted inside the three collections (Airplanes, Cars, Bikes) the url where to get these data.
I’ve overwrited the parse method, so I can modify the string that I get, order it, and put it in an object and inside localstorage. I need it to be persistent because I need to use those 3 data structure.
So with a fetch i get all those data and put them inside localstorage. Is it correct doing it that way?
Now i need to make other calls to the server, like “get the nearest car”.
In the view i need to see the color, name and model of the car, all that informations are inside the object “Cars” in localstorage.
In my view “showcars.view” I just call a non-backbone js, (not a collection, model or view) where i get all the informations i need. In this js i do:
var carmodel = new Car(); //car is the backbone model of the cars
carmodel.url = '/get/nearest/car'; //that give id of the nearest car
carmodel.fetch ({
success: function () {}
//here i search the Cars object for a car with the same id
//and get name, color, model and put them in sessionstorage
})
So after that call, in the view I can get the data I need from the sessionstorage.
Is that a bad way of doing things? If so, how i should fetch and analyze those informations? I should do all the calls and operations inside the models?
Thanks
This would be the way that you might implement what you want.
var Car = Backbone.Model.extend();
var Cars = Backbone.Collection.extend({
model: Car,
url: '.../cars'
});
var NearestCar = Backbone.Model.extend({
url: '...nearest/car'
});
var cars = new Cars();
var nearestCar = new NeaerestCar();
cars.fetch({
success: function() {
nearestCar.fetch({
success: function(model) {
var oneYouWant = cars.get(model.get('id'));
// do something with your car
// e.g.:
// var carView = new CarView({model: oneYouWant});
// $('body').append(carView.render().el);
});
});
});
});
In general, Backbone keeps everything in memory (that is, the browser memory) so there is no need to save everything to local storage, as long as your Collection object is somehow reachable from the scope you are sitting in (to keep things simple let's say this is the global window scope).
So in your case I will have something like three collections:
window.Cars
window.Airplanes
window.Bikes
Now you want the nearest. Assuming you are in a Backbone View and are responding to an event, in your place I would do something like this (just shows the meaningful code):
var GeneralView = Backbone.View.extend({
events: { "click .getNearestCar": "_getNearestCar" },
_getNearestCar: function () {
$.getJson('/get/nearest/car', function (data) {
// suppose the data.id is the id of the nearest car
var nearestCar = window.Cars.get(data.id)
// do what you plase with nearestCar...
});
}
});
I'm trying to figure out a Collection/Model system that can handle retrieving
data given the context it's asked from, for example:
Available "root" resources:
/api/accounts
/api/datacenters
/api/networks
/api/servers
/api/volumes
Available "sub" resources:
/api/accounts/:id
/api/accounts/:id/datacenters
/api/accounts/:id/datacenters/:id/networks
/api/accounts/:id/datacenters/:id/networks/:id/servers
/api/accounts/:id/datacenters/:id/networks/:id/servers/:id/volumes
/api/accounts/:id/networks
/api/accounts/:id/networks/:id/servers
/api/accounts/:id/networks/:id/servers/:id/volumes
/api/accounts/:id/servers
/api/accounts/:id/servers/:id/volumes
/api/accounts/:id/volumes
Then, given the Collection/Model system, I would be able to do things like:
// get the first account
var account = AccountCollection.fetch().first()
// get only the datacenters associated to that account
account.get('datacenters')
// get only the servers associated to the first datacenter's first network
account.get('datacenters').first().get('networks').first().get('servers')
Not sure if that makes sense, so let me know if I need to clarify anything.
The biggest kicker as to why I want to be able to do this, is that if the
request being made (ie account.get('datacenters').first().get('networks'))
hasn't be made (the networks of that datacenter aren't loaded on the client)
that it is made then (or can be fetch()d perhaps?)
Any help you can give would be appreciated!
You can pass options to fetch that will be translated to querystring params.
For example:
// get the first account
var account = AccountCollection.fetch({data: {pagesize: 1, sort: "date_desc"}});
Would translate to:
/api/accounts?pagesize=1&sort=date_desc
It is not quite a fluent DSL but it is expressive and efficient since it only transmits the objects requested rather than filtering post fetch.
Edit:
You can lazy load your sub collections and use the same fetch params technique to filter down your list by query string criteria:
var Account = Backbone.Model.extend({
initialize: function() {
this.datacenters = new Datacenters;
this.datacenters.url = "/api/account/" + this.id + '/datacenters';
}
});
Then from an account instance:
account.datacenters.fetch({data: {...}});
Backbone docs on fetching nested models and collections
I'm using Jerome's localStorage adapter with Backbone and it works great for collections.
But, now I have a single model that I need to save. So in my model I set:
localStorage: new Store("msg")
I then do my saves and fetch. My problem is that everytime I do a refresh and initialize my app a new representation of my model is added to localStorage, see below.
What am I doing wrong?
window.localStorage.msg = {
// Created after first run
"1de5770c-1431-3b15-539b-695cedf3a415":{
"title":"First run",
"id":"1de5770c-1431-3b15-539b-695cedf3a415"
},
// Created after second run
"26c1fdb7-5803-a61f-ca12-2701dba9a09e":{
"0":{
"title":"First run",
"id":"1de5770c-1431-3b15-539b-695cedf3a415"
},
"title":"Second run",
"id":"26c1fdb7-5803-a61f-ca12-2701dba9a09e"
}
}
I ran into same issue. Maybe you have something similar to this
var Settings = Backbone.Model.extend({
localStorage: new Store("Settings"),
defaults: { a: 1 }
});
var s = new Settings;
s.fetch();
I changed to
var s = new Settings({ id: 1 });
localStorage adapter check for id like
case "read": resp = model.id ? store.find(model) : store.findAll(); break;
so 0 or "" for id wont work and it will return all models in one
I'm new to backbone.js too, but it looks like the persistence model is analogous to database tables. That is to say, it's designed to create/delete/read records from a table. The localStorage adapter does the same, so what you are doing there is creating a Msg "table"
in localStorage, and creating a new Msg "record" each time, and the adapter gives each new Msg a unique id.
If you just have one object, it's probably easier to just use localStorage directly. The API is really straight forward:
localStorage.setItem("key","value");
Keep in mind that localStorage only deals with key/value pairs as strings, so you'd need to convert to/from string format.
Take a look a this question for more on doing that:
Storing Objects in HTML5 localStorage