Backbone without a datastore - javascript

I am working on an offline javascript application. It needs to support IE7 so localStorage is not an option. That said, the app does NOT need to persist any information (if you refresh everything gets wiped and that's OK).
So my question is, how do I set Backbone to just use a standard javascript variable (JSON) as my data store?
If I omit the model.url() method I get an error. I imagine this is simple, but I'm not sure what to do.
Thanks!

If you look at what the localStorage adapter is doing, you will find that it is overriding Backbone.sync. This is the module in Backbone which is responsible for storing/newing/retrieving/updating your data when you call new, save, fetch, etc.
By default, it uses a RESTful endpoint defined in the url of your model. If you use the LocalStorage override, it puts it in a local store.
If, instead, you just want to put it into an in-memory array, you would just override Backbone.sync the same way by defining what "read", "update", "create" and "delete" do. I would base it off of the backbone-localstorage.js adapter since it does most of what you want, but I would then store/retrieve from hash of id/object key/value pairs.

Simply do not use the save or create Collection methods.
Instead use store and add. These do not attempt to persist the data to storage.

Related

ember adapter pass id

I want to be able to pass an id to rest point while using ember data. My end-point looks like v3/enterprise/inventory/items/{id}/links. I want to inject the id while making the request such as this.store.findAll('each-item-links', { id: itemId }). However, it does not work. I extended the Ember REST adapter and override the namespace but nothing seems to be working.
If you're trying to request a single record through Ember Data, then you want to use findRecord instead of findAll.
Also, if you need control over how the URL is built (what you have there looks like it might not map to the RESTAdapter too cleanly) you can override the _buildURL method to change the URL that the request is sent to. It is given the ID from findRecord so you can generate the URL whatever you want. Technically this is "private API" but I wouldn't worry too much about overwriting that.
Edit: To avoid using private API, there is also a public buildURL method that can be used instead.

Architecture for temporary storing of values within a javascript library

I am currently writing a javascript library that wraps a REST API provided by a third party (intended to be used on server side, but wouldn't like to limit it to). One of the actions defined by the api is 'login' which gives me a session key that I need to use on further requests. Currently, everytime I go to use this library I need to login again as there is no persistence of this session key. My question is, what is the best way to persist it throughout a session?
My first instinct was to give the library a callback that would store it and a callback that would retrieve it and the implementation can determine how that session key is persisted:
var thirdPartyApi = new ThirdPartyApi({
loginCredentials: {..},
setSessionKeyCallback: function() {},
getSessionKeyCallback: function() {}
});
thirdPartyApi.makeSomeRequest('foo');
Can you recommend the best architecture for this problem?
It seems like you want to use the REST Api in a browser. There are some factors you need to take into account, such as, navigating away from the page and coming back to it later.
You can use Web Storage to store the key. There are two types, localStorage and sessionStorage. The only difference between then is that sessionStorage is deleted when the browser window is closed, while localStorage isn't. Web Storage is supported by all modern browsers and IE8+ http://www.w3schools.com/html/html5_webstorage.asp
The localStorage object can be used as such:
localStorage.setItem("bar", foo);
var foo = localStorage.getItem("bar");
localStorage.removeItem("bar");
sessionStorage object can be used the same way.
both localStorage and sessionStorage are global objects that can be accessed from anywhere, so there is no need for any special architecture on your ThirdPartyApi object.

Setting Backbone Marionette model via Global Object

In a Backbone.Marionette application I'm building, we have an authentication which returns a user object, which we in turn stash at App.User (so it's not truly global).
The problem I'm having is that I don't want to make a call to an API endpoint to access the various properties of the returned user object. The specific use case I'm working through right now is that the returned user object contains data about which modules in the app the user is permitted to access (no worries about security, we've clarified that it's OK that the user can spoof a var in their console to gain access to the UI, the services layer will prevent their actions in such an area from being meaningful).
My goal is to avoid a scenario where every time I need access to users.appAccess (a hypothetical array that lists the modules I can access) in order to instantiate it as a model I have to call out to a URL / API endpoint by declaring it in the collection's definition like this:
Entities.Access = Backbone.Collection.extend({
url: 'http://example.com/users/:id/access/',
}
});
Removing the url property from the above code throws an error, and I can pass it a function which returns empty but this doesn't play nice with
var access = new Entities.Access()
access.fetch();
when attempting to pass the fetched collection to a Marionette CollectionView. Should I simply avoid using the fetch() method and keep it otherwise a typical (albeit hack-ish) Backbone collection definition?
Backbone allows you to populate a Backbone collection either as you have (with an empty constructor) or with a collection of data. It sounds like you've already got the data stored in the User object, and you want to push this information to the Entities.Access collection.
var access = new Entities.Access(user.access);
I'm with you, this feels a bit like a hack, but since Backbone doesn't support this nativly there isn't much else you can do. Have a look at Backbone-Relational or supermodel.js. These projects provide better forms of model nesting than the default implementation.

Client side data storage

I have the following situation: the user submits a form, I fetch the data from the server via an Ajax request and displays a chart. However, I want to give the user the option to display the data in the chart in table form or export as csv after he had submitted the form.
I was wondering what's the best solution to store the data, considering that I don't want the data to persist if the user opens a new window to submit the form again for example.
The application is in Rails.
Thanks.
You have a few options:
Cookies
LocalStorage
SessionStorage
More info: https://developer.mozilla.org/en/DOM/Storage
Non-standard:
window.name can store anywhere from 1mb up to 10mb depending on the browser. This is more of a hack, but is fairly stable. You would need to implement your own accessor/setter methods on this, where localStorage and sessionStorage have API's built in.
Personally i would recommend local storage if all your users browsers support it.
Its very simple to use and you can access it using these to methods.
localStorage.getItem("Itemkey");
localStorage.setItem("Itemkey","value");
localStorage.removeItem("ItemKey");
Its always a good way to go and this means you can assign each window a differnt local storage key and even remove the item when the window is closed, or unloaded !
For reference I found this very useful: http://diveintohtml5.info/storage.html
And combine it with storing JSON objects ( http://www.json.org/js.html ) and you have a very fast,simple and easy to use solution. OR even just store a string,array or what ever is required.

Are there any Backbone.js tutorials that teach ".sync" with the server?

I read many Backbone.js tutorials, but most of them deal with static objects.
Of course, I have data on the server. I want a tutorial that shows how backbone.js can communicate with the server to fetch data, post data, etc.
This is .sync, right? I read the backbone.js documentation, but still fuzzy on how to use this feature.
Or can someone show me an example?
According to: http://documentcloud.github.com/backbone/#Sync
Backbone.sync is the function that Backbone calls every time it
attempts to read or save a model to the server.
But when? Where do I put the function? I don't know how to use it, and the documentation doesn't give any examples. When does the data get loaded into my models? I get to define when...right?
You never really have to look at .sync, unless you plan to overwrite it. For normal uses, you can simply call model.save() whenever you want and that will execute a post or put (depending on whether the record exists already). If you want to get the data from your backend, use collection.fetch()
You'll of course also need to specify a URL, do so through your collection attribute, collection.url
You can override Backbones native sync functionality if you override it:
Backbone.sync = function() {
//Your custom impl here
}
After that this function is called whenever you call a backbone function like .save() on models or .fetch() on collections. You do not have to care about data transport anymore.
I would suggest taking a look into Backbones source and look how the default sync function is implemented. Then create your own or adopt your server to support the native function.
They are not free, but the following screencasts both have a piece on backend work and how to send data to and get data from Backbone.
Tekpub is a 9 part screencast about asp.net MVC3, with the whole 6th part about using backbone to write an admin module to manage productions. it shows all about handling routing in MVC3 and sending & receiving data
Peepcode
http://peepcode.com/products/backbone-js about basic backbone stuff
http://peepcode.com/products/backbone-ii about interactivity
http://peepcode.com/products/backbone-iii about persistance (it's this third one you will need for server connection information).

Categories

Resources