How to use can-connect - 10 common examples

To help you get started, we’ve selected a few can-connect examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github canjs / can-connect / src / fixture / fixture.js View on Github external
can.fixture["-" + types[1] + "Update"] = methods.update;
					can.fixture["-" + types[1] + "Destroy"] = methods.destroy;
					can.fixture["-" + types[1] + "Create"] = methods.create;
				}
			};
		} else {
			filter = make;
			var initialItems = count;
			reset = function(){
				items = initialItems.slice(0);
			};
		}
		

		// make all items
		helpers.extend(methods, {
			findAll: function (request) {
				
				request = request || {};
				//copy array of items
				var retArr = items.slice(0);
				request.data = request.data || {};
				//sort using order
				//order looks like ["age ASC","gender DESC"]
				(request.data.order || [])
					.slice(0)
					.reverse().forEach(function (name) {
						var split = name.split(" ");
						retArr = retArr.sort(function (a, b) {
							if (split[1].toUpperCase() !== "ASC") {
								if (a[split[0]] < b[split[0]]) {
									return 1;
github canjs / can-connect / src / fixture / fixture.js View on Github external
// If the fixture setting is a string, we just change the URL of the
	// AJAX call to the fixture URL.
	if (typeof settings.fixture === "string") {
		var url = settings.fixture;

		// If the URL starts with //, we need to update the URL to become
		// the full path.
		if (/^\/\//.test(url)) {
			// this lets us use rootUrl w/o having steal...
			url = getUrl(settings.fixture.substr(2));
		}

		if (data) {
			// Template static fixture URLs
			url = helpers.sub(url, data);
		}

		delete settings.fixture;

		//!steal-remove-start
		log("looking for fixture in " + url);
		//!steal-remove-end

		// Override the AJAX settings, changing the URL to the fixture file,
		// removing the data, and changing the type to GET.
		settings.url = url;
		settings.data = null;
		settings.type = "GET";
		if (!settings.error) {
			// If no error handling is provided, we provide one and throw an
			// error.
github canjs / can-connect / docs / demos / basics.html View on Github external
TodoList.prototype = Object.create(Array.prototype);

TodoList.prototype.completed = function(){
  return this.filter(function(todo){
    return todo.status === "complete";
  });
};

TodoList.prototype.active = function(){
  return this.filter(function(todo){
    return todo.status !== "complete";
  });
};

// A connection that gets todos data
var todoConnection = connect(["constructor","data-url"],{
  url: "/todos",
  list: function(listData, set){
  	return new TodoList(listData.data);
  },
  instance: function(props) {
  	return new Todo(props);
  }
});

// Trap ajax requests to return and modify the following `todo` object.

fixture({
	"GET /todos": function(request){
		return {
			data: [
				{id: 1, name: "mow lawn", status: "assigned"},
github passbolt / passbolt-appjs / app / model / map / group.js View on Github external
.then(() => {
      // Destroy the local entity.
      this.destroy();
    })
    .then(null, jqXHR => {
      let jsonData = {};
      if (jqXHR.responseText) {
        try {
          jsonData = $.parseJSON(jqXHR.responseText);
        } catch (e) { }
      }
      return Ajax.handleError(request, jsonData);
    });
};

Group.connection = connect([connectParse, connectDataUrl, connectConstructor, connectMap], {
  Map: Group,
  List: Group.List,
  url: {
    resource: '/',
    destroyData: function() {
      // @see Group::delete() function
      return Promise.resolve({});
    },
    getData: function(params) {
      params = params || {};
      params['api-version'] = 'v2';
      return Ajax.request({
        url: 'groups/{id}.json',
        type: 'GET',
        params: params
      });
github passbolt / passbolt-appjs / app / model / map / user.js View on Github external
this.profile.assign({avatar: data.profile.avatar});
        this.dispatch('updated');
        Ajax._unregisterRequest(request);
        return Promise.resolve(this);
      }), jqXHR => {
      let jsonData = {};
      if (jqXHR.responseText) {
        try {
          jsonData = $.parseJSON(jqXHR.responseText);
        } catch (e) { }
      }
      return Ajax.handleError(request, jsonData);
    });
};

User.connection = connect([connectParse, connectDataUrl, connectConstructor, connectMap], {
  Map: User,
  List: User.List,
  url: {
    resource: '/',
    createData: function(params) {
      return Ajax.request({
        url: 'users.json?api-version=v2',
        type: 'POST',
        params: params
      });
    },
    updateData: function(params) {
      // Filter the attributes that need to be send by the request.
      const _params = User.filterAttributes(params);
      return Ajax.request({
        url: 'users/{id}.json?api-version=v2',
github bitovi-components / bit-c3 / bit-c3 / node_modules / can-connect / src / fall-through-cache / fall-through-cache.html View on Github external
import connect from "can-connect";
import "can-connect/data/url/";
import "can-connect/constructor/";
import "can-connect/constructor/store/";
import "can-connect/data/localstorage-cache/";
import "can-connect/fall-through-cache/";
import fixture from "can-fixture";
import $ from "jquery";
import helpers from "can-connect/helpers/";

var cache = connect(['data-localstorage-cache'],{
	name: "todos"
});

// A connection that gets todos data
var todosConnection = connect([
	"fall-through-cache",
	"constructor",
	"constructor-store",
	"data-url"],{
  url: "/todos",
  cacheConnection: cache
});



var todoItem = function(todo) {
	var li = $("<li>");
	var update = function(){
		if(todo.complete) {
			li.css("text-decoration","line-through");
		} else {</li>
github canjs / can-connect-feathers / service / service.js View on Github external
"use strict";
var connect = require('can-connect');

function getIdProp (Model) {
	var algebraIdProp;
	var algebraClause = Model.algebra && Model.algebra.clauses && Model.algebra.clauses.id;
	if (algebraClause) {
		algebraIdProp = Object.keys(algebraClause)[0];
	}
	if (!algebraIdProp && !Model.idProp) {
		throw new Error('An idProp was not set in the Model for ' + Model + '. Things may not work as expected.');
	}
	return algebraIdProp || Model.idProp;
}

module.exports = connect.behavior('data/feathers-service', function (base) {
	var helpURL = 'https://canjs.com/doc/can-connect-feathers.html';
	if (!this.feathersService) {
		throw new Error('You must provide a feathersService to the feathers-service behavior: ' + helpURL);
	}

	var service = this.feathersService;

	return {
		init: function () {
			base.init.apply(this, arguments);
			var self = this;
			// Connect to real-time events.
			service.on('created', function (message) { self.createInstance(message); });
			service.on('updated', function (message) { self.updateInstance(message); });
			service.on('patched', function (message) { self.updateInstance(message); });
			service.on('removed', function (message) { self.destroyInstance(message); });
github canjs / can-connect / data / callbacks / callbacks.js View on Github external
* @signature `connection.destroyedData(data, params, cid)`
	 *
	 *   Called with the resolved response data
	 *   of [can-connect/connection.destroyData]. The result of this function will be used
	 *   as the new response data.
	 *
	 *
	 *   @param {Object} data The raw data returned by the response.
	 *   @param {Object} params The parameters used to make this request.
	 *   @param {Number} cid The cid of the instance created.
	 *   @return {Object} The raw data this request represents.
	 */
	destroyData: "destroyedData"
};

module.exports = connect.behavior("data/callbacks",function(baseConnection){

	var behavior = {
	};

	// overwrites createData to createdData
	each(pairs, function(callbackName, name){

		behavior[name] = function(params, cid){
			var self = this;

			return baseConnection[name].call(this, params).then(function(data){
				if(self[callbackName]) {
					return self[callbackName].call(self,data, params, cid );
				} else {
					return data;
				}
github canjs / can-connect / constructor / callbacks-once / callbacks-once.js View on Github external
*/
	"updatedInstance",
	/**
	 * @function can-connect/constructor/callbacks-once/callbacks-once.destroyedData destroyedData
	 * @parent can-connect/constructor/callbacks-once/callbacks-once
	 *
	 * Called with the resolved response data
	 * of [can-connect/connection.destroyData]. The result of this function will be used
	 * as the new response data.
	 */
	"destroyedInstance"
];



module.exports = connect.behavior("constructor/callbacks-once",function(baseConnection){

	var behavior = {
	};

	// overwrites createData to createdData
	forEach.call(callbacks, function(name){
		behavior[name] = function(instance, data ){

			var lastSerialized = this.getInstanceMetaData(instance, "last-data-" + name);

			var serialize = sortedSetJSON(data);
			if(lastSerialized !== serialize) {
				var result =  baseConnection[name].apply(this, arguments);
				this.addInstanceMetaData(instance, "last-data-" + name, serialize);
				return result;
			}
github bitovi-components / bit-c3 / bit-c3 / node_modules / can-connect / src / data / localstorage-cache / localstorage-cache.js View on Github external
var indexOf = function(connection, props, items){
	var id = connection.id(props);
	for(var i = 0; i &lt; items.length; i++) {
		if( id == connection.id(items[i]) ) {
			return i;
		}
	}
	return -1;
};

var setAdd = function(set, items, item, algebra){
	return items.concat([item]);
};


module.exports = connect.behavior("data-localstorage-cache",function(baseConnect){

	var behavior = {
		// ## Helpers


		// a map of each id to an instance
		_instances: {},
		getSetData: function(){

			var sets = {};
			var self = this;
			forEach.call((JSON.parse(localStorage.getItem(this.name+"-sets"))|| []), function(set){
				// make sure we actually have set data
				 var setKey = sortedSetJSON(set);

				if( localStorage.getItem(self.name+"/set/"+setKey) ) {