Use of the url parameter in Backbone.Model.extend - backbone.js

I'm new to backbone and i'm wondering what is the url parameter used for as
app.FormModel = Backbone.Model.extend({
defaults: {
success: false,
saveData: ''
}
});
will give me a
Uncaught Error: A "url" property or function must be specified
what is url that I need to provide to extend method
According to the documentation it says
Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic.
What does it mean by resources.

Change
app.FormModel = Backbone.Model.extend({
to
app.FormModel = new Backbone.Model.extend({

If you'd like to send/retrieve data to server, backbone needs to know where the server is. The URL is exactly this.
If you don't set this property and try to sync with server, backbone will throw this exception.
http://backbonejs.org/#Model-url

Related

ExtJs Model Proxy vs. Store Proxy

OK, I'm stuck on what should be a basic task in ExtJs. I'm writing a simple login script that sends a user name and password combination to a RESTful web service and receives a GUID if the credentials are correct.
My question is, do I use a Model Proxy or a Store Proxy?
To my understanding, Models represent a single record, whereas Stores are for handling sets of data containing more than one record. If this is correct then it would seem that a Model proxy is the way to go.
Following Sencha's documentation at http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.Model the code would look something like this:
Ext.define('AuthenticationModel', {
extend: 'Ext.data.Model',
fields: ['username', 'password'],
proxy: {
type: 'rest',
url : '/authentication'
}
});
//get a reference to the authentication model class
var AuthenticationModel = Ext.ModelManager.getModel('AuthenticationModel');
So far everything is OK, until the next step:
//Use the configured RestProxy to make a GET request
AuthenticationModel.load('???', {
success: function(session) {
console.log('Login successful');
}
});
The load() method for the Model class is a static call expecting a single unique identifier. Logins typically depend upon two factors, username and password.
So it appears Store proxies are the only way to validate someone's username and password credential combination in ExtJS. Can someone verify and explain? Any help to understand this would be greatly appreciated.
You just need to know the following:
The store will use it's own proxy if you configured one for this
instance and if not he takes the proxy from the model.
So you can easily go with two proxy configurations to enable the multi-CRUD operations on the store and the single-CRUD operations on the Models. Note the the static load method of the Model expects the model id because it is supposed to load a model by just one Id (yes, composite keys are not supported). You will also have to fetch the model instance in the callback (As you did).
Back to your Username/password problem
You may apply your session Model with a custom 'loadSession' method
loadSession: function(username,password, config) {
config = Ext.apply({}, config);
config = Ext.applyIf(config, {
action: 'read',
username: username,
password: password
});
var operation = new Ext.data.Operation(config),
scope = config.scope || this,
callback;
callback = function(operation) {
var record = null,
success = operation.wasSuccessful();
if (success) {
record = operation.getRecords()[0];
// If the server didn't set the id, do it here
if (!record.hasId()) {
record.setId(username); // take care to apply the write ID here!!!
}
Ext.callback(config.success, scope, [record, operation]);
} else {
Ext.callback(config.failure, scope, [record, operation]);
}
Ext.callback(config.callback, scope, [record, operation, success]);
};
this.getProxy().read(operation, callback, this);
}
Now call this instead of load.
I found it in the documentation of sencha App Architecture Part 2
Use proxies for models:
It is generally good practice to do this as it allows you to load and
save instances of this model without needing a store. Also, when
multiple stores use this same model, you don’t have to redefine your
proxy on each one of them.
Use proxies for stores:
In Ext JS 4, multiple stores can use the same data model, even if the
stores will load their data from different sources. In our example,
the Station model will be used by the SearchResults and the Stations
store, both loading the data from a different location. One returns
search results, the other returns the user’s favorite stations. To
achieve this, one of our stores will need to override the proxy
defined on the model.

Using a Backbone Collection without a data source (no url)

First time posting here... looking forward to see how it all works, but have really appreciated reading other's questions & answers.
I am using backbone for a small app and have found it helpful to use a collection to store some information that is only required during the current session. (I have a number of collections and all the others connect to my API to store/retrieve data).
I read here (in backbone.js can a Model be without any url?) that it is possible, and even good to use a collection without providing a url.
Now I would like to add a row of data to the collection... simple:
myCollection.create(data);
but of course that now throws an error:
Uncaught Error: A "url" property or function must be specified
Is there any way to use a Backbone collection, be able to add new rows of data (models) to it, but not sync to any sort of data source. Or can you suggest another solution.
I guess I could just use an object to hold the data, but I was enjoying the consistency and functionality.
I am using Backbone.Marionette if that has any impact.
Thanks in advance.
One thing you could do is override the Backbone.Model methods that communicate with the server, i.e. sync, fetch, and save... for example:
var App = {
Models: {},
Collections: {}
};
App.Models.NoUrlModel = Backbone.Model.extend({});
App.Models.NoUrlModel.prototype.sync = function() { return null; };
App.Models.NoUrlModel.prototype.fetch = function() { return null; };
App.Models.NoUrlModel.prototype.save = function() { return null; };
App.Collections.NoUrlModels = Backbone.Collection.extend({
model: App.Models.NoUrlModel,
initialize: function(){}
});
var noUrlModels = new App.Collections.NoUrlModels();
noUrlModels.create({'foo': 'bar'}); // no error
// noUrlModels.models[0].attributes == {'foo': 'bar'};
See Demo

Backbone TODO model --> save method

I am following the annotated source code at:
http://backbonejs.org/docs/todos.html
The model is:
var Todo = Backbone.Model.extend({
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
toggle: function() {
this.save({done: !this.get("done")});
}
});
My question is:
What happens when this.save is called? I know that the collection uses local storage, but how does the model by itself work?
Model has a url & urlRoot methods where you define the Rest end point to your server.
So it will try to connect to that point and execute the code that corresponds to that particular point. So this saves the new state of the model to your Server.
But because in the case you are referring to , Local storage adapter is used , the changes will be persisted in the browser. So url method is not required.
But because of this if you try to open the same in a different browser, you won't see any changes as the changes are are on the browser and not on the server.

Backbone.js DELETE request not firing

I'm trying to get the backbone.js DELETE request to fire, but don't see any requests being made in my console.
I have collection model like so:
var Model = Backbone.Model.extend(
{
urlRoot: '/test',
defaults:{}
});
var TableList = Backbone.Collection.extend(
{
url: '/test',
model: Model
});
In my view I'm running this:
this.model.destroy();
Everything seems to be running fine, I can see output coming from the remove function that calls the destroy so I know it's getting there plus it also successfully runs an unrender method that I have. Can't see any requests being made to the sever though?
If I am not mistaken, you have to have an id property on your model to ensure that it hits the correct url. IE if your model was...
var Model = Backbone.Model.extend({
url: '/some/url'
});
var model = new Model({
id: 1
});
model.destroy(); // I THINK it will now try and DELETE to /some/url/1
Without an id it doesn't know how to build the url correctly, typically you'd fetch the model, or create a new one and save it, then you'd have a Url...
See if that helps!
I found the issue to my problem, thought not a solution yet. I'm not sure this is a bug with backbone or not, but I'm using ajaxSetup and ajaxPrefilter. I tried commenting it out and it worked. I narrowed it down to the ajaxSetup method and the specifically the use of the data parameter to preset some values.
Have you tried using success and error callbacks?
this.model.destroy({
success : _.bind(function(model, response) {
...some code
}, this),
error : _.bind(function(model, response) {
...some code
}, this);
});
Might be instructive if you're not seeing a DELETE request.

How do I specify various URLs in a backbone app?

I need one of my backbone models to hit a variety of URLs depending on the type of action being performed. How do I determine the action within the URL function so that I can specify the appropriate URL? For example:
DELETE: /myapipath/itemtype/id/
POST: /myapipath/special-path/
GET: /myapipath/special-path/?code=ABC
I know how to tell the difference between a POST and everything else: this.isNew()
But how do I tell the difference between a DELETE and a GET in a custom model.url function?
Please don't suggest that I change the server-side api. That isn't up to me.
Thanks!
Conceptually the url of a Backbone model is the primary GET url of the resource. To use a different url for some of the actions, override the model's sync function. Fortunately, Backbone makes it easy to override:
window.MyModel = Backbone.Model.extend({
// ... other stuff ...
url: '/myapipath/special-path/?code=ABC',
methodUrl: {
'create': '/myapipath/special-path/',
'delete': '/myapipath/itemtype/id/'
},
sync: function(method, model, options) {
if (model.methodUrl && model.methodUrl[method.toLowerCase()]) {
options = options || {};
options.url = model.methodUrl[method.toLowerCase()];
}
Backbone.sync(method, model, options);
}
}
Edit: I took another look at the Backbone source and noticed that it merges the whole options argument to build the params, not options.params, and updated my example accordingly.

Resources