I'm building an app with Appcelerator.
I use Backbone to get data from database.
So I have build this code to get data from database:
var collection = Alloy.createCollection("SocialHistoryDAO");
collection.fetch();
Now I want to apply a where at this collection. So I use this code:
collection.where(id : 5);
Then this code works, but now I want to apply this filter:
"WHERE ID != 5";
It is possible to do this?
EDIT:
this is my SocialHistoryDAO model:
exports.definition = {
config: {
columns: {
"ID": "INTEGER PRIMARY KEY AUTOINCREMENT",
"IdOmnia": "INTEGER",
"DateStart": "text",
"DateEnd": "text",
"Quantity": "decimal",
"Code": "text",
"CodeSystem": "text",
"DisplayName": "text",
"DisplayNameTarget": "text",
"UnityMeasure": "text",
"StateID": "INTEGER"
},
adapter: {
type: "sql",
collection_name: "SocialHistoryDAO",
idAttribute: "ID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
destroyAll : function(opt) {
var db = Ti.Database.open(this.config.adapter.db_name);
db.execute("DELETE FROM " + this.config.adapter.collection_name);
db.close();
this.models = [];
if (!opt || !opt.silent) { this.trigger("reset"); }
return this;
}
});
return Collection;
}
};
If you're using Backbone, then you're also using Underscore (or LoDash).
This can be accomplished using either:
var newArray = _.filter(collection.models, function(model) { return model.get('ID') != 5; });
or
var newArray = _.reject(collection.models, function(model) { return model.get('ID') == 5; });
Related
I have this jSON structure.
{
"customer": {
"idcustomer": 2,
"name": "test_2",
"vat": "test_vat_2",
"obs": "obs_2",
"deleted": 0
},
"addresses": [
{
"idaddress": 9,
"street": "street_2_9",
"number": "number_2_9",
"country": "country_2_9",
"default": true,
"label": "labe_2_9",
"deleted": 0
},
{
"idaddress": 10,
"street": "1",
"number": "number_2_9",
"country": "country_2_10",
"default": false,
"label": "label_2_10",
"deleted": 0
}
],
"contacts": []
}
With knockout mapping plugin I am able to generate a knockout observable object. However, when trying to add extra properties to the object using the mapping parameter I find some issues. The goal is to add "SelectedAddress" to the main object and in each address a "defaultLabel" observabale.
Currently i have this mapping structure to add the property to the address children:
var mapping = {
'addresses': {
create: function (options) {
return (new (function () {
this.defaultLabel= ko.computed(function () {
return (this.default() == 0) ? "" : this.label();
}, this);
ko.mapping.fromJS(options.data, {}, this);
})());
}
},
}
and this to add the "SelectedAddress" to the main JSON:
create: function (options) {
return new function () {
var model = ko.mapping.fromJS(options.data, {}, this);
// Direccion
model.direccionSeleccionada = ko.observable();
model.getDireccion = ko.computed({
read: function() {
if (model.direccionSeleccionada() != null) {
return model.direccionSeleccionada();
} else {
return [{
idaddress: -1,
street : '',
number: '',
country: '',
default: '',
label: '',
deleted: '',
}];
}
},
write: function(value) {
self.direccionSeleccionada(value);
},
owner: self
});
}
}
I can not find a way to have them both
Ideas?
Thank you
I figured it out. Just for someone; Just as simple as when generatint he mapping of "addresses", add inside another mapping for it.
var mapping = {
create: function (options) {
return new function () {
var model = ko.mapping.fromJS(options.data, {
'adresses': {
create: function (options) {
return (new(function () {
this.labelDefault= ko.computed(function () {
return (this.default() == 0) ? "" : this.label();
}, this);
ko.mapping.fromJS(options.data, {}, this);
})( /* call the ctor here */ ));
}
},
}, this);
model.direccionSeleccionada = ko.observable();
model.getDireccion = ko.computed({
read: function () {
if (model.selectedAddress() != null) {
return model.selectedAddress();
} else {
return [{
idaddress: -1,
street: '',
number: '',
country: '',
default: '',
label: '',
deleted: ''
}];
}
},
write: function (value) {
self.selectedAddress(value);
},
owner: self
});
}
}
}
Thank you!
[Previously titled "How to get 1 record from a list..."]
I am very new to GraphQL and trying to understand how to get 1 record from query.
This is the result of my current query:
{
"data": {
"todos": null
}
}
I am not sure what is wrong. I would like the result to be this:
{
"data": {
"todos": {
"id": 1,
"title": "wake up",
"completed": true
}
}
}
Here is my code that I've created as I try to learn GraphQL.
schema.js:
var graphql = require('graphql');
var TODOs = [
{
"id": 1,
"title": "wake up",
"completed": true
},
{
"id": 2,
"title": "Eat Breakfast",
"completed": true
},
{
"id": 3,
"title": "Go to school",
"completed": false
}
];
var TodoType = new graphql.GraphQLObjectType({
name: 'todo',
fields: function () {
return {
id: {
type: graphql.GraphQLID
},
title: {
type: graphql.GraphQLString
},
completed: {
type: graphql.GraphQLBoolean
}
};
}
});
var queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: function () {
return {
todos: {
type: new graphql.GraphQLList(TodoType),
args: {
id: { type: graphql.GraphQLID }
},
resolve: function (source, args, root, ast) {
if (args.id) {
return TODOs.filter(function(item) {
return item.id === args.id;
})[0];
}
return TODOs;
}
}
}
}
});
module.exports = new graphql.GraphQLSchema({
query: queryType
});
index.js:
var graphql = require ('graphql').graphql;
var express = require('express');
var graphQLHTTP = require('express-graphql');
var Schema = require('./schema');
var query = 'query { todos(id: 1) { id, title, completed } }';
graphql(Schema, query).then( function(result) {
console.log(JSON.stringify(result,null," "));
});
var app = express()
.use('/', graphQLHTTP({ schema: Schema, pretty: true }))
.listen(8080, function (err) {
console.log('GraphQL Server is now running on localhost:8080');
});
To run this code I just run node index from the root directory. How can I get one specific record returned by the records id?
You have the wrong type for the todos field of your queryType. It should be TodoType, not a list of TodoType. You're getting an error because GraphQL expects to see a list, but your resolver is just returning a single value.
By the way, I suggest passing the graphiql: true option to graphqlHTTP, which will let you use GraphiQL to explore your schema and make queries.
I have a select box that I am populating with data from a json file using the code below:
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: {
take: 100,
skip: 0
},
}).done(function (data) {
$.each(data, function (i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
})
})
};
getType();
The problem is that the returned value type.name has loads of duplicates in it, I would like to filter out these duplicates to only show each unique value one time. Im a bit stuck on where to start with this though so help would be greatly appreciated :)
Using Array.prototype.filter and creating an array to track unique names, you can build up a filtered data array to then iterate over to display your unique datasets.
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: { take: 100, skip: 0 },
})
.done(function(data) {
var filteredData = [];
var uniqueNames = [];
data.filter(function (data) {
if (uniqueNames.indexOf(data.type.name) < 0) {
uniqueNames.push(data.type.name);
filteredData.push(data);
}
});
$.each(filteredData, function(i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
})
})
};
getType();
You can write a condition to append options only if options with same text does not exist in the #choose select, using selector [text="someText"].
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: {
take: 100,
skip: 0
},
}).done(function (data) {
$.each(data, function (i, item) {
if($("#choose").children('option[text="' + item.type.name + '"]').length == 0){
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
}
})
})
};
getType();
You can use filter like this :
var unique=data.filter(function(item,i,a){
return i==data.indexOf(item.type.name);
});
All you need to do is to filter out the value that's already been found. Please find comments inline for more info.
//Sample data
var data = [
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 1" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 4" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 3" },
}
]
//Create an empty object
var $items = $();
$.each(data, function(i, item) {
//Construct the option
var $option = $('<option/>', {text: item.type["name"]});
//Add it to the bucket only if it's not already added!
if (!$items.filter(":contains(" + item.type["name"] + ")").length) {
$items = $items.add($option);
}
});
//Always append outside the loop!
$("#choose").append($items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choose"></select>
Try this code snippets.
.done(function(data) {
var records=[];
$.each(data, function (i, el) {
if ($.inArray(el, records) === -1) records.push(el); //filters the duplicate elements
});
$.each(records, function(i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
});
});
Update:
Try this code snippet if you want to filter out the name from the json data variable.
.done(function(data) {
var records=[], nameList = [];
$.each(data, function (i, elem) {
nameList.push(elem.type.name);
});
$.each(nameList, function (i, el) {
if ($.inArray(el, records) === -1) records.push(el);
});
$.each(records, function(i, item) {
var option = $('<option>').text(item)
option.appendTo("#choose");
});
});
I have a array of events and i want to make relation between these array's object.
array:
[{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
} {
'area': 'sindh',
'site': 'karachi',
'link': 'http: //karachi.com'
}]
Know i want to make the relation like
{
"area": "punjab",
"site": [
{
"name": "lahore",
"link": [
{
"name": "http://sargodha.com",
}
]
},
{
"name": "sargodha",
"link": [
{
"name": "http://sargodha.com",
}
]
}
]
},
{
"area": "sindh",
"site": [
{
"name": "karachi",
"link": [
{
"name": "http://karachi.com",
}
]
}
}
here is my code which i wrote:
function isinarrayfilters(matchingObject, targetArray, key) {
var existindex = -1;
$.each(targetArray, function(index, array) {
if (array.key == matchingObject.key) {
//Object exist in array
existindex = index;
}
});
return existindex;
}
generatedRelationArray = [];
$.each(alertsJson, function(index, alertJson) {
inarrayindex = isinarrayfilters(alertJson.area, relationArray,'area');
if (inarrayindex == -1) {
key = alertJson.site
generatedsites = {
"area": alertJson.area,
"site": []
}
relationArray.push(generatedsites);
}
});
Know anyone guide me how i append the site into the related area.
I have to run loop again and try to check the exist method and get the index and will push the sites into it?
A Format preserved answer:
var generate = function(list) {
var resultList = [];
var tmpStoreRef = {};
$.each(list, function(id, item) {
var area = item.area
,site = item.site
,link = item.link;
if (typeof tmpStoreRef[area] === 'undefined') {
tmpStoreRef[area] = {
area: area,
site: []
}
resultList.push(tmpStoreRef[area]);
}
tmpStoreRef[area].site.push({
name: site,
link: link
});
});
return resultList;
};
You can use query-js to accomplish this
Assuming your original array is stored in data
var res = data.groupBy(function(e){ return e.area; });
That would create a slightly different structure:
{
"punjab" : [{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
}],
"sindh": [...]
}
If you need that explicit structure then you can do this instead
var res = data.groupBy(function(e){ return e.area; })
.each(function(e){
return {
area : e.key,
site : e.value.select(function(e){
return {
name : e.site,
linkm : [e.link]
};
});
});
I've created a post that's supposed to be explanatory of what query-js is and how to use it
I was wondering if it was possible to filter a model like how a collection can be filtered?
I'm doing a search functionality for a sport site and I want to be able filter the search results by type, i.e. football, tennis, basket-ball, swimming, athletic, etc...
Here's my code (check the filterSearch() method):
define([
'jquery',
'backbone',
'underscore',
'models/model'],
function($, Backbone, _, Model){
var Search = Model.extend({
urlRoot: '/search',
defaults: {
query: ''
},
initialize: function(attrs, options) {
if (typeof options === 'object') {
this.router = options.router;
}
},
filterSearch: function(type) {
this.filter(function(data) {
return data.get(type);
});
}
});
return Search;
});
JSON:
[
{
"search": [
{
"result": {
"query": "Vettel is world champion"
},
"type": "Formula 1",
"id": 1
},
{
"result": {
"query": "Romario of Brazil world cup 1994"
},
"type": "football",
"id": 2
},
{
"result": {
"query": "federe won again"
},
"type": "tennis",
"id": 3
}
]
}
]
Is there a specific reason you are using a Model for this case rather than a Backbone Collection? You could easily have a Model for a single search result :
var searchResult = Backbone.Model.extend({});
and a collection to represent the search
var Search = Backbone.Collection.extend({
model : searchResult,
urlRoot: '/search',
filterSearch: function(type) {
return this.where({'type' : type});
},
parse: function(response) {
return response.search;
}
});
Otherwise just search over the array provided in the model:
...
filterSearch: function(type) {
return _.where(this.get('search'), {'type' : type});
}