addInstanceReference
Add a reference to the instanceStore so an instance can be easily looked up.
connection.addInstanceReference( instance )
Adds a reference to an instance by id to the instanceStore. Keeps a count of the number of references, removing the instance from the store when the count reaches 0.
Parameters
- instance
{Instance}
:the instance to add
Use
The instanceStore contains a mapping of instances keyed by their
id. The instanceStore is used to prevent creating
the same instance multiple times, and for finding active instance for a given id. Instances need to be added to
this store for this to work. To do this, call addInstanceReference
:
// a basic connection
var constructorStore = require("can-connect/constructor/store/");
var constructor = require("can-connect/constructor/");
var dataUrl = require("can-connect/data/url/");
var todoConnection = connect([dataUrl, constructorStore, constructor], {
url: "/todos"
});
var originalTodo;
// get a todo
todoConnection.get({id: 5}).then(function( todo ){
// add it to the store
todoConnection.addInstanceReference(todo);
originalTodo = todo;
});
Now, if you were to retrieve the same data sometime later, it would be the same instance:
todoConnection.get({id: 5}).then(function( todo ){
todo === originalTodo // true
});
The .getData
response data (underlying the call to todoConnection.get
) is passed, along with the existing todo
instance (originalTodo
) to updatedInstance. That updates the shared
instance with the newly retrieved data.
All the referenced instances are held in memory. Use deleteInstanceReference to remove them.
Typically, addInstanceReference
is called when something expresses interest in the instance, such
as an event binding, and deleteInstanceReference
is called when the interest is removed.