I made a JS template
<div class="slider">
<script id="jstemplate" type="js/template">
<div class="items">
<span class="name"> {{name}} </span> : <span class="address">{{address}}</span>
</div>
</script>
</div>
and JSON object each
var JSONObject = [
{
name: 'Nyonya',
address: '199 Grand Street New York, NY 10013, United States'
},
{
name: 'Mulberry Project',
address: '149 Mulberry Street New York, NY 10013, United States'
},
{
name: 'Sweet & Vicious',
address: '5 Spring Street New York, NY 10012, United States'
},
],
template = $.trim($('#jstemplate').html());
$.each(JSONObject, function(i,v){
var temp = template.replace( /{{name}}/ig, v.name)
.replace( /{{address}}/ig, v.address);
console.log(temp);
$('.slider').append(temp);
});
Please check ONLINE SAMPLE
I can get the output successfully, my question is that,
How to make the output displays and loop one by one (eg. every 5 seconds), just like a slideshow?
Try
(function() {
var JSONObject = [{
name : 'Nyonya',
address : '199 Grand Street New York, NY 10013, United States'
}, {
name : 'Mulberry Project',
address : '149 Mulberry Street New York, NY 10013, United States'
}, {
name : 'Sweet & Vicious',
address : '5 Spring Street New York, NY 10012, United States'
}], template = $.trim($('#jstemplate').html());
var $ct = $('.slider');
$.each(JSONObject, function(i, v) {
var temp = template.replace(/{{name}}/ig, v.name).replace(
/{{address}}/ig, v.address);
$(temp).hide().appendTo($ct);
});
function x(){
var $item = $ct.children('.items').first().stop().fadeIn().delay(3000).fadeOut(function(){
$(this).appendTo($ct);
x();
})
}
x();
})();
Demo: Fiddle
http://jsfiddle.net/F98zF/8/
$('.slider div').hide().first().show();
setInterval(
function(){
$('.slider div:first').fadeOut().next().fadeIn().end().appendTo(".slider");}
,3000);
Related
Is possible to create an ko.observable array and populate it using an array object?
My goal here is to create a ko.observable array with all the description/objects that are with the original array.
//Sample data the original data is coming from an socket query and being push on the array("people")
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "friend"
}
];.
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail#me.com",
type: "friend"
}
];
var quotesarray = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
ko.applyBindings(new quotesarray(people));
console.log(people);
You just needed to make it items instead of quotesarray
var people = [
{ name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail#me.com", type: "family" },
{ name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail#me.com", type: "friend" }
];
var quotesarray = function(items){
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function(){
if (this.itemToAdd() != ""){
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
ko.applyBindings(new quotesarray(people));
console.log(people);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>name</th><th>address</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
</tr>
</tbody>
</table>
You can create an observableArray to which the socket writes messages. You subscribe to the array to be automatically notified when the contents change (i.e. after every write by the socket).
In the subscribe callback you empty the array and add the items to your viewmodel's property.
If you expect to receive many rapidly succeeding messages, you can rateLimit the array to which you write to ensure you don't update the DOM too many times.
Here's an example. The explanations are in the code comments.
const UPDATE_EVERY_MS = 500;
// The observable array the socket writes to
const received = ko.observableArray([])
// Use a rateLimit extension if you expect to
// receive many updates from your socket
.extend({ rateLimit: UPDATE_EVERY_MS });
// The observable array in your viewmodel
const rendered = ko.observableArray([]);
received.subscribe(items => {
// Write "inbox" to viewmodel's list
rendered(rendered().concat(items));
// Clear received without triggering notification
items.length = 0;
});
ko.applyBindings({ items: rendered });
// Mock a socket that writes to `received`
setInterval(() => received.push(Math.random()), 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: rendered">
<li data-bind="text: $data"></li>
</ul>
I'm new to javascript. i'm having difficulty printing the data from the location ObservableArray. The data - bind works and i could list out the data from the location ObservableArray at the view but can't print it out on the console. i have been on it for hours now, any help would be appreciated. thank you
Here is the ViewModel
let MapViewModel = function() {
let map
let geocoder;
let self = this;
self.location = ko.observableArray([]);
for (let i = 0; i < locationList.length; ++i) {
self.location.push(new Location(locationList[i]));
}
console.log(this.location()); // Location, Location, Location, Location, Location, Location, Location]
console.log(this.location()[0].name); // Location {name: ƒ, address: ƒ} ...
console.log(this.location().length); //length is 7
}
let Location = function(data) {
this.name = ko.observable(data.name);
this.address = ko.observable(data.address);
}
ko.applyBindings(new MapViewModel());
Here is the Binding Code`
<div class="menu_item_container">
<h1>Neighborhood Map</h1>
<input type="text" id="search" data-bind= 'value:filterLocations, valueUpdate: 'afterKeyDown',value:filterLocations' placeholder="Search Locations...">
<hr>
<nav id=nav>
<ul data-bind='foreach:location'>
<li data-bind="text:name"></li>
</ul>
</nav>
</div>
LocationList
let locationList = [{
name: 'Brooklyn Museum',
address: '200 Eastern Pkwy, Brooklyn, NY 11238'
}, {
name: 'Empire State Building',
address: '350 5th Ave, New York, NY 10118'
}, {
name: 'Statue of liberty',
address: 'New York, NY 10004'
}, {
name: 'Rockefeller Center',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'Brooklyn Bridge',
address: 'Brooklyn Bridge, New York, NY 10038'
},
{
name: 'Time Square',
address: '45 Rockefeller Plaza, New York, NY 10111'
},
{
name: 'World Trade Center',
address: '285 Fulton St, New York, NY 10007'
},
];
This can unwrap observable to regular js and convert this to single string (if needed) and then u can print it console :
let locationsJSON = ko.toJS(self.location);
let locationsString = JSON.stringify(locationsJSON);
I have a AngularJS app where I have an array defined that has a group of dealers. Something like this:
$scope.dealers = [{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude"
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website:"site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
A user will input their zip code, and then using the Google Geocode API, I convert their zip code to lat/long coordinates and find their closest dealer based off of coordinates between them, and all of the dealers.
That is working fine.
Here is where I need help. Each dealer has a territory (in the array as counties) that needs to be checked first, before finding the closest dealer, because some dealers have counties in their territories that are actually geographically closer to another dealer.
I have a var that stores the users County based on their zip. So I need to make an IF statement that checks the userZip variable against the dealers array to see if that county exists anywhere in the array. If it does, then I need to return the name of that dealer. If it does not, I will have an ELSE statement that just runs the function I already have, which will just find the closest dealer to their location.
You can use Array.prototype.find()
let dealers = [{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
{
name: "Dealer Name",
address: "Address goes here",
website: "site.com",
lat: "latitude",
lng: "longitude",
territory: ['County1', 'County2', 'County3']
},
];
let country = 'County2';
let found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");
//another case
country = 'NotAnywhere';
found = dealers.find(d => d.territory.includes(country));
if(found)
console.log(found);
else
console.log("..find closest...");
could anyone help me with this please, used Canada as example:
var CA = {
name: "Canada Name",
iso: "CA",
percentage: "23.4",
color: getColor(23.4)
};
$(function() {
$('#world-map').vectorMap({
map: 'world_mill_en',
.
.
onRegionTipShow: function(event, wrap, code) {
wrap.html('hello ' + code); // working, outputs "hello CA"
console.log(CA.name); // working, outputs "Canada Name"
console.log(code.name); // not working - undefined
},
.
.
How can I use the "code" to refer to the variable (CA in this case)?
As I see code outputs a string but I just can not turn it to a form that works
Thx
You would need to further wrap your CA object in another object, something like this:
var langs = {
CA: {
name: "Canada Name",
iso: "CA",
percentage: "23.4",
color: getColor(23.4)
}
}
You can then access the properties of langs using bracket notation. So assuming code = 'CA' in your example:
onRegionTipShow: function(event, wrap, code){
wrap.html('hello ' + code); // = 'hello CA'
console.log(langs[code].name); // = 'Canada Name'
},
update I
Based on feedback, I've changed var maps to var adds.
problem description
I'm working on Rails 3.0.0.beta2, following Advanced Rails Recipes "Recipe #32, Mark locations on a Google Map" and I hit a road block: I do not see a google map. My #adds view uses #adds.to_json to connect the google maps api with my model. My database contains "latitude" "longitude", as floating points. And the entire project can be accessed at github.
Can you see where I'm not connecting the to_json output with the javascript correctly? Can you see other glairing errors in my javascript? Thanks in advance!
My application.js file:
function initialize() {
if (GBrowserIsCompatible() && typeof adds != 'undefined') {
var adds = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.addControl(new GLargeMapControl());
function createMarker(latlng, add) {
var marker = new GMarker(latlng);
var html="<strong>"+add.first_name+"</strong><br />"+add.address;
GEvent.addListener(marker,"click", function() {
map.openInfoWindowHtml(latlng, html);
});
return marker;
}
var bounds = new GLatLngBounds;
for (var i = 0; i < adds.length; i++) {
var latlng=new GLatLng(adds[i].latitude,adds[i].longitude)
bounds.extend(latlng);
map.addOverlay(createMarker(latlng, adds[i]));
}
map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
}
}
window.onload=initialize;
window.onunload=GUnload;
Layouts/adds.html.erb:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true_or_false&key=ABQIAAAAeH4ThRuftWNHlwYdvcK1QBTJQa0g3IQ9GZqIMmInSLzwtGDKaBQvZChl_y5OHf0juslJRNx7TbxK3Q" type="text/javascript"></script>
<% if #adds -%>
<script type="text/javascript">
var adds = <%= raw #adds.to_json %>;
</script>
<% end -%>
Rails Console Output
a = Add.all
=> [#<Add id: 1, first_name: "Jason", last_name: "Wade", address: "225 Anzavista Ave, San Francisco, CA", address2: "", zip: "94115", city: "San Francisco", phone: "415-280-6678", float: nil, campaign_id: 1, email: "jwade#gmail.com", employer: "Google", occupation: "", created_at: "2010-04-06 14:00:36", updated_at: "2010-04-06 14:00:36", latitude: 37.779623, longitude: -122.445662>]
ruby-1.9.1-p378 > a.to_json
=> "[{\"address\":\"225 Anzavista Ave, San Francisco, CA\",\"address2\":\"\",\"campaign_id\":1,\"city\":\"San Francisco\",\"created_at\":\"2010-04-06T14:00:36Z\",\"email\":\"jwade#gmail.com\",\"employer\":\"Google\",\"first_name\":\"Jason\",\"float\":null,\"id\":1,\"last_name\":\"Wade\",\"latitude\":37.779623,\"longitude\":-122.445662,\"occupation\":\"\",\"phone\":\"415-280-6678\",\"updated_at\":\"2010-04-06T14:00:36Z\",\"zip\":\"94115\"}]"
var bounds = new GLatLngBounds;
should be
var bounds = new GLatLngBounds();
And you were initially correct:
var map = new GMap2(document.getElementById("map"));