How to get typeahead JS working with my json file - typeahead

I would like to make a simple autocomplete with Typeahead JS but i cant make it work. I followed the instructions in the manual but I am not sure what I am doing wrong here. I cant get the right value out of the json file. Its an array with objects, and I just want the country names. Shouldnt be that hard I think. I doesnt display anything. Please help!
You can find the typeahead js files at "Getting Started" on the Typeahead Github page.
This is my code:
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="typeahead.jquery.min.js"></script>
<script src="bloodhound.min.js"></script>
</head>
<body>
<div id="prefetch">
<input class="typeahead" type="text" placeholder="Countries">
</div>
<script>
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 4,
prefetch: {
url: 'countries.json',
}
});
countries.clearPrefetchCache();
countries.initialize();
$('#prefetch .typeahead').typeahead(null, {
name: 'countries',
displayKey: 'country',
source: countries.ttAdapter(),
});
</script>
</body>`
Json file (countries.json):
[
{
"country": "Holland",
"city": "Amsterdam"
},
{
"country": "Belgium",
"city": "Brussel"
},
{
"country": "Germany",
"city": "Berlin"
},
{
"country": "France",
"city": "Paris"
}
]

Your datumTokenizer is not configured correctly. It should look like this.
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country'),
Here is a demo
I know the question is old but I hope this helps.

Another easy-way, it helped me, if your json is like this...
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$('#states').typeahead({
name: 'states',
limit: 10,
minLength: 1,
source: function (query, process) {
states = [];
map = {};
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
});

Related

Marking certain appointments as not selectable in Kendo Scheduler for ASP.NET MVC

I have the Scheduler loading multiple appointments. Some of those appointments should be read-only and the user should not be able to select them. Some of the appointments they should be able to select and edit, though. The logic for this is determined on the server and passed as a field in the payload on load.
I've attempted to hook into several client side events, such as Edit, MoveStart, and ResizeStart and cancel the edit events. This does work, however I would like the user to not even be able to select the event.
I do not see any client side events for Selecting that I can cancel.
I did attempt to iterate through the appointments on DataBound, but was unsure of how to prevent selecting at that point.
I suggest using a custom event template with and edit button and setting editable and selectable properties as false for the scheduler.
<script id="event-template" type="text/x-kendo-template">
<div>
<label>Title: #: title #<label>
# if (allowEdit) { #
<button style="margin-left:50px;" onclick="editSchedulerEvent(#:id#)">Edit</button>
# } #
</div>
<div>
Attendees:
# for (var i = 0; i < resources.length; i++) { #
#: resources[i].text #
# } #
</div>
</script>
<div id="scheduler"></div>
<script>
function editSchedulerEvent(id){
var scheduler = $("#scheduler").data("kendoScheduler");
var event = scheduler.dataSource.get(id);
scheduler.editEvent(event);
}
$("#scheduler").kendoScheduler({
date: new Date("2013/6/6"),
eventTemplate: $("#event-template").html(),
editable: false,
selectable: false,
dataSource: [
{
id: 1,
start: new Date("2013/6/6 08:00 AM"),
end: new Date("2013/6/6 09:00 AM"),
title: "Interview",
atendees: [1,2],
allowEdit: true
},
{
id: 2,
start: new Date("2013/6/6 10:00 AM"),
end: new Date("2013/6/6 11:00 AM"),
title: "Interview",
atendees: [3,4],
allowEdit: false
}
],
resources: [
{
field: "atendees",
dataSource: [
{ value: 1, text: "Alex" },
{ value: 2, text: "Bob" },
{ value: 3, text: "John" },
{ value: 4, text: "Jane" }
],
multiple: true
}
]
});
</script>
</body>
</html>

Import JSON file to JavaScript function

Is it possible to import a JSON file into a JavaScript function? If yes, how can this be done the best practice way?
Below is my code with a few json rows and It'd be insane to have a million rows hardcoded in the function.
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
} );
</script>
You can do this:
var availableTags = JSON.parse("{{ context|escapejs }}");
and then you can loop over normally in Javascript.
Check out the codepen. It clearly works at the front end, the issue might be at the backend.

Correct way to persist embedded relationships in ember-data in a Ember-cli application

I am facing a situation in which I need to persist an embedded relationship into database. I am describing a similar situation in this question. It is an ember-cli project.
I have two models:
//app/model/post.js
import DS from 'ember-data';
var Post = DS.Model.extend({
entry: DS.attr('string'),
comments: DS.hasMany('comment')
});
export default Post;
//app/models/comment.js
import DS from 'ember-data';
var Comment = DS.Model.extend({
text: DS.attr('string'),
post: DS.belongsTo('post')
});
export default Comment;
1 Serializer:
//app/serializers/post.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {
embedded: 'always'
}
}
});
1 Route:
//app/routes/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('post', 1);
},
setupController: function(controller, model) {
var newComment = this.store.createRecord('comment', {});
newComment.set('text', 'xxxx comment');
model.get('comments').pushObject(newComment);
model.save().then(function(){
console.log(model.toJSON());
comments = model.get('comments');
comments.forEach(function(comment){
console.log("Comment: " + comment.get('text'));
console.log("Comment id: " + comment.get('id'));
});
});
}
});
So, the GET call in model hook the server returns:
// GET /posts/1
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
}
]
}
}
When in the setupController hook, I add a new comment to the post and save it, its actually sending a PUT request with the following body:
// PUT /posts/1 -- Request
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
},
{
"post": "1",
"text": "xxxx comment"
}
]
}
}
The server returns the following output:
// PUT /posts/1 -- Response
{
"posts": {
"id": "1",
"entry": "This is first post",
"comments": [
{
"id": "1",
"post": "1",
"text": "This is the first comment on first post"
},
{
"id": "2",
"post": "1",
"text": "This is the second comment on first post"
},
{
"id": "3",
"post": "1",
"text": "xxxx comment"
}
]
}
}
But now in the console log I get the following output:
Comment: This is the first comment on first post
Comment id: 1
Comment: This is the second comment on first post
Comment id: 2
Comment: xxxx comment
Comment id: 3
Comment: xxxx comment
Comment id: null
Why is the new comment returned with id is added to the post's comments and is not replacing the comment?
Am I doing anything wrong or I need to add something else for this?
Ember Data would have no exact way of recognizing the difference between a record that user attempted to save and a record a different user attempted to save.
All it can safely know is that a new record with a new id came back (since there was no unique identifier on the record before, and you didn't specify to save that exact record).
In a non multi-user world, it could assume the new record should replace the existing record, but the Embedded Record stuff just isn't that smart yet.
1. Delete the record after you save (cause you know it'll get duped, hacky)
var comments = model.get('comments');
comments.pushObject(newComment);
model.save().then(function(){
comments.popObject(newComment);
newComment.deleteRecord(); // not really necessary
...
});
2. Save the record from the comment's point of view (cheapest and cleanest, might be a bit of additional server side logic for you)
newComment.save();

Ember Data nested Models

I'm using EmberJs and Ember-Data in a Google App Engine project which uses NDB. In the database I have Host, Probe and Check entities. The database model doesn't really matter as long as I have my REST api in order but for clarity here are my database Classes:
class Host(ndb.Model):
hostName = ndb.StringProperty()
hostKey = ndb.Key('Host', 'SomeHostId')
class Probe(ndb.Model):
checkName = ndb.StringProperty()
probeKey = ndb.Key('Host', 'SomeHostId', 'Probe', 'SomeProbeId')
class Check(ndb.Model):
checkName = ndb.StringProperty()
checkKey = ndb.Key('Host', 'SomeHostId', 'Probe', 'SomeProbeId', 'Check', 'SomeCheckId')
I've added the keys in order to show that each host has some probes running on them and each probe performs some checks.
Host
Probe
Check
In my App.Js I have defined the following models:
App.Host = DS.Model.extend({
hostName: DS.attr('string')
probes: DS.hasMany('probe',{async:true})
});
App.Probe = DS.Model.extend({
host: DS.belongsTo('host'),
probeName: DS.attr('string')
checks: DS.hasMany('check',{async:true})
});
App.Check = DS.Model.extend({
probe: DS.belongsTo('probe'),
hostName: DS.attr('string')
});
I have defined the following router:
App.Router.map(function() {
this.resource('hosts', function(){
this.resource('host', { path:':host_id'}, function(){
this.resource('probes', function(){
this.resource('probe', { path:':probe_id'}, function(){
this.resource('checks', function(){
this.resource('check', { path:':check_id'}, function(){
});
});
});
});
});
});
});
And in AppEngine if have built the following URL paths:
app = webapp2.WSGIApplication([
('/', MainHandler),
webapp2.Route('/hosts', HostsHandler),
webapp2.Route('/hosts/<hostId>/', HostHandler),
webapp2.Route('/hosts/<hostId>/probes', ProbesHandler),
webapp2.Route('/hosts/<hostId>/probes/<probeId>/checks', ChecksHandler),
webapp2.Route('/hosts/<hostId>/probes/<probeId>/checks/<checkId>/', CheckHandler)
])
http://example.com/hosts returns:
{
"hosts": [
{
"hostName": "SomeHostName1",
"id": "SomeHostId1"
},
{
"hostName": "SomeHostName2",
"id": "SomeHostId2"
}
]
}
http://example.com/hosts/SomeHostId1/probes returns:
{
"probes": [
{
"probeName": "SomeProbeName1",
"id": "SomeProbeId1",
"host_id": "SomeHostId1"
},
{
"probeName": "SomeProbeName2",
"id": "SomeProbeId2",
"host_id": "SomeHostId1"
}
]
}
http://example.com/hosts/SomeHostId1/probes/SomeProbeId1/checks returns:
{
"checks": [
{
"checkName": "SomeCheckName1",
"id": "SomeCheckId1",
"probe_id": "SomeProbeId1"
},
{
"checkName": "SomeCheckName2",
"id": "SomeCheckId2",
"probe_id": "SomeProbeId1"
}
]
}
My templates are:
<script type="text/x-handlebars" id="host">
<h3>{{hostName}}</h3>
{{#link-to 'probes' probes}}probes{{/link-to}}
{{outlet}}
</script>
<script type="text/x-handlebars" id="probes">
{{#each probe in probes}}
Probe: {{probe.probeName}}
{{#link-to 'checks' probe.checks}}checks{{/link-to}}
{{/each}}
{{outlet}}
</script>
<script type="text/x-handlebars" id="checks">
{{#each check in checks}}
Check: {{check.checkName}}
{{/each}}
</script>
Now I have all this... but no clue how to tie it up together so that Ember-Data makes the right http requests. So far I've only seen request go to http://example.com/modelName/
Currently Ember Data does not support this type of nested routes for API endpoints. There's been some talk about this, but it doesn't seem to be making any forward progress.
I don't know anything about App engine, but if you could obtain a config like this, for ember-data rest adapter
app = webapp2.WSGIApplication([
('/', MainHandler),
webapp2.Route('/hosts', HostsHandler),
webapp2.Route('/hosts/<hostId>', HostHandler),
webapp2.Route('/probes', ProbesHandler),
webapp2.Route('/probes/<probeId>', ProbesHandler),
webapp2.Route('/checks/', CheckHandler)
webapp2.Route('/checks/<checkId>/', CheckHandler)
])
And the response to http://example.com/hosts should return a json array hosts:[{},{}] and to http://example.com/hosts/1 a json representing a host object host:{} and the same for the other AppEngine routes
You have defined the Host model twice, I think that shouldn't have been the case. I am pretty new to ember and haven't used async:true feature, but I have been able to do things like(but I hadn't used nested route):
App.Host = DS.Model.extend({
hostName: DS.attr('string')
probes: DS.hasMany('probe')
});
App.Probe = DS.Model.extend({
probeName: DS.attr('string')
checks: DS.hasMany('check')
});
App.Check = DS.Model.extend({
checkName: DS.attr('string')
});
and you can spin up a rest api for host that returns :
{
"hosts": [
{
"hostName": "SomeHostName1",
"id": "SomeHostId1",
"probes":["p1","p2"]
},
{
"hostName": "SomeHostName2",
"id": "SomeHostId2",
"probes":["p2","p3"]
}
],
"probes": [
{
"probeName": "SomeProbeName1",
"id": "p1",
"checks":["c1","c2"]
},
{
"probeName": "SomeProbeName2",
"id": "p2",
"checks":["c2","c3"]
}
],
"checks": [
{
"checkName": "SomeCheckName1",
"id": "c1"
},
{
"checkName": "SomeCheckName2",
"id": "c2"
}
]
}
In my case I didn't have nested route but I think we should be able to set the controller content from the master payload somehow since all the required content are in store already! I don't know if it was of any help, but this is something I would also like to know the answer of.

CRUD operations using Ember-Model

Here,I am trying to implement CRUD operations using ember-model.
I am totally new to ember environment,actually i don't have much understanding of ember-model.
Here,i am trying to add new product and delete existing one.I am using inner node of fixture
i.e. cart_items.My this fixture contains two node i.e. logged_in and cart_items and this what my fixture structure :
Astcart.Application.adapter = Ember.FixtureAdapter.create();
Astcart.Application.FIXTURES = [
{
"logged_in": {
"logged": true,
"username": "sachin",
"account_id": "4214"
},
"cart_items": [
{
"id": "1",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "2",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "3",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
}
]
}
];
I want to this fixture struture only to get data in one service call from server.
Now,here is my code which i am using to add and delete product from cart_items
Astcart.IndexRoute = Ember.Route.extend({
model: function() {
return Astcart.Application.find();
}
});
Astcart.IndexController = Ember.ArrayController.extend({
save: function(){
this.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({name: this.get('newProductDesc'),qty: this.get('newProductQty'),price: this.get('newProductPrice'),subtotal: this.get('newProductSubtotal')});
new_cart_item.save();
});
},
deleteproduct: function(product){
if (window.confirm("Are you sure you want to delete this record?")) {
this.get('model').map(function(application) {
application.get('cart_items').deleteRecord(product);
});
}
}
});
But when i am trying to save product i am getting an exception
Uncaught TypeError: Object [object global] has no method 'get'
And when i am trying to delete product i am getting an exception
Uncaught TypeError: Object [object Object] has no method 'deleteRecord'
Here,i also want to implement one functionality i.e. on every save i need to check if that product is already present or not.
If product is not present then only save new product other wise update existing product.
But i don't have any idea how to do this?
I have posted my complete code here.
Can anyone help me to make this jsfiddle work?
Update
I have updated my code here with debugs.
Here, i am not getting any exception but record is also not getting delete.
I am not getting what is happening here?
Can anyone help me to make this jsfiddle work?
'this' context changes within your save method. You need to use the 'this' of the controller and not the map functions. Try this:
save: function(){
var self = this;
self.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({
name: self.get('newProductDesc'),
qty: self.get('newProductQty'),
price: self.get('newProductPrice'),
subtotal: self.get('newProductSubtotal')
});
new_cart_item.save();
});
}