Check if element is not in an array to open a window - javascript

what I am doing here is some kind of a chat interface with your online and offline contacts which you can drag around the window. I m stuck trying to create a function to check if you already opened a chat window to avoid duplicated windows. This is the link of what i got so far. s2.enigmind.com/jgonzalez/nodeChat I hope you guys can see it.
This is the function in which I append the window elements this function get some parameters that i obtain from a JSON, the parameters are user id name and status.
function displayChatWindow(user, status, avatar, id){
var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar, userId: id});
stackingWidth = stackingWidth - boxWidth;
/*console.log(stackingWidth);*/
$("body").prepend(template);
$(".messages-container").slimScroll({
height: '200',
size: '10px',
position: 'right',
color: '#535a61',
alwaysVisible: false,
distance: '0',
railVisible: true,
railColor: '#222',
railOpacity: 0.3,
wheelStep: 10,
disableFadeOut: false,
start: "bottom"
});
$("#" + id).css({
top: absoluteY,
left: stackingWidth
});
$("#" + id).find(".minimize").on("click", displayOthersChat);
$(".chat input, .chat textarea").on("focus", cleanInputs);
$(".chat input, .chat textarea").on("blur", setInputs);
addWindow(id, stackingWidth);
}
what I have in my global scope is an array called var openedWindows = []; and in this array I am appending the user id and position with the addWindow function.
function addWindow(id, offset){
openedWindows.push({
id: id,
offset: offset
})
}
So far, every time i open a new window this one is added to the array, I've been using a for loop to see if the user and id is already in the array, but i don't actually know how to structure my code, because there is no way to check at the first time if the user is in the array because the array is empty, I will appreciate if you guys know how i could achieve this, I know my code is not the best, all this is for my learning purposes so i accept all kind of tips! Thank you very much.

you are already using underscore.js , so why not use its _.each() function to loop over all entries in openedWindows:
function addWindow(id, offset) {
var found = false;
_.each(openedWindows, function(el, idx) {
// 'el' is an item in openedWindows, and 'idx' is its position in the array
if (el.id === id) {
found = true;
}
});
if (found === false) {
openedWindows.push({
id: id,
offset: offset
});
}
}

Related

JointJS show message on validation Failed

I'm trying to show a toaster when the user tries to connect two elements that cannot be linked. The problem is JointJS calls the function validateConnection for all elements on the Graph when I start dragging the arrow not only when the arrow reaches the target, so I cannot place the toaster code there. I'm looking a way to check if a invalid connection attempt was done.
I know that I can listen to
paper.on('link:connect', function(linkView, evt, elementViewConnected, magnet, arrowhead) {console.log('Valid connection');});
But only to valid connections. Is there a way to get a invalid connection attempt?
My Paper:
const paper = this.paper = new rappid.joint.dia.Paper({
width: 1000,
height: 1000,
gridSize: 10,
drawGrid: true,
model: graph,
multiLinks: false,
linkPinning: false,
markAvailable: true,
perpendicularLinks: true,
defaultLink: function (cellView, magnet, link) {
return LinksService.getMyLink(cellView.model.attributes.link, data);
},
validateConnection: function (cellViewS, magnetS, cellViewT, magnetT, end) {
const idS = cellViewS.model.id;
const idT = cellViewT.model.id;
const links = appInstance.graph.getLinks();
if (flowContext.existsConnection(idS, idT, links)) {
return false;
}
return true;
},
});
validateConnection is used to prevent the user from creating invalid connections at all while they are interacting with the link. If you want to react to invalid connections (with a toast/message) you can use allowLink instead. (doc: https://resources.jointjs.com/docs/jointjs/v2.1/joint.html#dia.Paper.prototype.options.allowLink)

How do I make an image provided by an api as the background image of my div in jQuery and node?

I am trying to create a search engine for movies with an api provided by the movie database (tmdbs). I want to have a div popup for each movie that has a title similar to the one the user types in to the database. Right now I chose the movie Lucy as my experiment. I want the poster image provided in the first result of the api when I search for Lucy to be the background image of the div I am creating, I cannot seem to be able to accomplish this. My ultimate goal is to create a series of results with divs that have background images as provided by the first 20 results in the api. Here is my code:
$('#search').keypress(function(e) {
if (e.which == 13) {
var movie = $('#search-input').val();
$('form#login').submit();
console.log('onclick fun', movie)
makeCall(movie);
return false;
}
});
function makeCall(aMovie) {
console.log('makecall', aMovie);
link = url + aMovie;
console.log(link);
$.ajax({
method: "GET",
url: link,
success: function(data) {
console.log("the data -->", data);
getData(data);
},
})
}
function getData(responseData) {
var poster = responseData.results[0].poster_path;
appendToDom(poster);
}
function appendToDom(poster) {
var aPoster = $('<div>');
var movie_poster = 'https://image.tmdb.org/t/p/w1280' + poster;
console.log(movie_poster);
aPoster.css({
'float': 'left',
'margin': 10,
'margin-left': 37,
'margin-top': 20,
'width': 200,
'height': 300,
'font-size': 36,
'color': 'black',
'background-size': '200px 300px',
'background-image': 'https://image.tmdb.org/t/p/w1280/rwn876MeqienhOVSSjtUPnwxn0Z.jpg' //'url("./../images/question.jpg")'
})
$(main).append(aPoster);
}
Here is a screenshot of what I'm looking for. Instead of the question marks I want the movie posters to come up.
enter image description here
I'm really sorry for the long post. I hope someone can help me:)
Thanks a lot in advance!
var aPoster = $('');
and
var aPoster = $('div');
return totally different values. Might want to check that.

want to specify each row of tableView from data from Appcelerator cloud

Im developing an android app with PC with titanium/appcelerator cloud service.
I want to have the facebook's newsfeed page where list of user's post comes down.
I have managed to do this with tableView with each row displaying each post from the server.
The problem is that I somehow can not get the individual user;s photo AND (that there is button for each posts) if i clikc this button, it doesnt give me the user information of that specific user but the user of the first post.
for example, if user1, user2, user3 posts one each,
the list page shows post1, post2, post3 respectively.
If i click the button of post2(which is send message button), it tries to send it to user1 not user2.
here is my code.
been stuck for last 2 days,,
THANKS!
profileimage is the variable for photo
shopping is the variable for the message send button
win.addEventListener('open', function () {
Cloud.Posts.query({
page: 1,
per_page: 20,
order: "-created_at"
}, function (e) {
if (e.success) {
status.hide();
var tbl_data = [];
for (var i = 0; i < e.posts.length; i++) {
var post = e.posts[i];
-- there are some code here ---
var profileimage = Ti.UI.createView({
backgroundImage: post.user.photo.urls.medium_500,
backgroundColor: '#fffff',
width: 90,
height: 90,
borderRadius: 22,
top:20, left: 10
});
var shopping = Ti.UI.createView({
backgroundImage: 'shopping.png',
width: 35,
height: 35,
top: 70,
right: 10
});
shopping.addEventListener('click', function(){
//alert(post);
var tradewin,tradeinc;
tradeinc = require('trade');
tradewin = new tradeinc.trade1(post);
tradewin.open();
});
It seems as though your issue stems from adding the click event listeners for all of the shopping views inside the for loop. When the shopping click function is actually called due to user action it accesses the most recent value of post which will always be the value of post at the end of the for loop: e.posts[e.post.length - 1]. I've modified your code to alleviate this issue:
win.addEventListener('open', function () {
Cloud.Posts.query({
page: 1,
per_page: 20,
order: "-created_at"
}, function (e) {
if (e.success) {
status.hide();
var tbl_data = [];
for (var i = 0; i < e.posts.length; i++) {
var post = e.posts[i];
-- there are some code here ---
var profileimage = Ti.UI.createView({
backgroundImage: post.user.photo.urls.medium_500,
backgroundColor: '#fffff',
width: 90,
height: 90,
borderRadius: 22,
top:20, left: 10
});
var shopping = Ti.UI.createView({
backgroundImage: 'shopping.png',
width: 35,
height: 35,
top: 70,
right: 10
});
// This wrapper function returns a callback function
// for your click event that also maintains the correct
// value of `post`
function getShoppingClickCallback(associatedPost) {
return function () {
var tradewin, tradeinc;
tradeinc = require('trade');
tradewin = new tradeinc.trade1(associatedPost);
tradewin.open();
};
}
// This line calls the `getShoppingClickCallback` function and
// passes the associated `post` object. The returned value of
// `getShoppingClickCallback` is a callback function.
shopping.addEventListener('click', getShoppingClickCallback(post));
Using a helper function like getShoppingClickCallback when adding event listeners in a for loop is a really helpful pattern. I suggest trying this out in your project and seeing if your issue persists. I hope it doesn't! :)

pass selected tableview row data from one window to next window in titanium

I have developing the titanium tableview. here if i have select any row , need to pass the row values from one window to next window.
But From my code .,
Am getting the list of table rows successfully. the row data also passed.
But i have facing a problem ., First time am clicking one row means the null value is passed . After that come back the list view and click another row means the previous selected row id is passed to next window .why i have facing this issue ? what's problem here ? Please give me a solution .
I have using below code :
dataArray = [];
for(var i=0; i<json.length; i++){
var row = Ti.UI.createTableViewRow({
className: 'row',
objName: 'row',
folder_id:json[i].folder_id,
layout : 'horizontal',
touchEnabled: true,
width: "100%",
height: Ti.UI.SIZE,
});
row.add(Ti.UI.createLabel({
text: json[i].folder_id,
title: json[i].folder_id,
left: 10,
top: 5,
width: 0,
visible : false,
font: { fontSize: '18dp' },
color: '#040404',
wordWrap: true,
height: Ti.UI.SIZE,
ellipsize: true
}));
row.add(Ti.UI.createLabel({
text: json[i].folder_name,
title: json[i].folder_name,
left: 10,
top: 5,
width: 100,
font: { fontSize: '18dp' },
color: '#040404',
wordWrap: true,
height: Ti.UI.SIZE,
ellipsize: true
}));
dataArray.push(row);
};
$.FoldertableView.setData(dataArray);
$.FoldertableView.addEventListener('click', function(e){
Ti.API.info("folder_id"+ e.rowData.folder_id );
var managereditfolder =Alloy.createController('editfolder').getView();
Ti.App.Properties.setString("folder_id", e.rowData.folder_id);
managereditfolder.open();
});
editfolder.js
folder_id = Ti.App.Properties.getString("folder_id");
Ti.API.info("Edit Folder folder_id"+ folder_id );
here am getting the output like :
folder_id 14
[WARN] : Invalid value auto specified for property top
[INFO] : Edit Folder folder_id null
folder_id 5
[WARN] : Invalid value auto specified for property top
[INFO] : Edit Folder folder_id 14
Please check my code and give me a solutions
You do not need to save your data to Ti.App.Properties to pass it to another view controller, you can rather do the following:
Pass data to the controller you create
var managereditfolder = Alloy.createController('editfolder', { folderId: e.rowData.folder_id } ).getView();
In editfolder.js you will receive the folder id by
// This holds all the Objects you pass along when
// creating the controller
var args = arguments[0] || {};
// Hence, your folderId is args.folderId
Ti.API.debug( args.folderId );
P.S.
Don't forget to always put a var before any new variable you declare, otherwise you might get in trouble with the global scope!
$.FoldertableView.addEventListener('click', function(e){
Ti.API.info("folder_id"+ e.rowData.folder_id );
var managereditfolder = Alloy.createController('editfolder').getView();
managereditfolder.folder_id = e.rowData.folder_id;
managereditfolder.open();
});
and in editfolder.js you can simply access it by
$.editFolderWin.folder_id

Stuck building a javascript object dynamically

I have a bunch of interactive activities which have been written in flash by reading in all the parameters from an XML file. We are moving away from FLASH and so I am writing a script which will read in the XML elements I need and dynamically build a javascript object containing all the elements and their properties. In the end, I pass the object through a JSON.stringify() and pass back a JSON-ized version.
I'm reading in the XML using an ajax call with JQUERY and then a mix of JS and JQUERY. I like jquery for its DOM selectors.
I'm learning all this stuff as I go along and i'm not a developer by trade so i've hit a wall when I get to the point where I need to process a bunch of elements with .each(). I'm guessing its a syntax thing though i'm not sure. Everything was working great until it came time to adding the "panels" which in the XML looks like +...
I have to process each panel.
$.ajax({
type: "GET",
url: "activity.xml",
dataType: "xml",
success: function(xml) {
var activity = {
title : {
text: $(xml).find('title').text(),
xpos: $(xml).find('title').attr('xpos'),
ypos: $(xml).find('title').attr('ypos')
},
rubric : {
text: $(xml).find('rubric').text(),
xpos: $(xml).find('rubric').attr('xpos'),
ypos: $(xml).find('rubric').attr('ypos')
},
panels: {
$(xml).find('panel').each(function() {
panel :{width: $(this).attr('width'),
height: $(this).attr('height'),
xpos: $(this).attr('xpos'),
ypos: $(this).attr('ypos')
}});// end .each()
}// end panels object
});//end ajax.get(xml)
var activity_json = JSON.stringify(activity);
Im certain its not done this way but i don't know how it should be.
Thanks in advance
Your problem must be here
panels: {
$(xml).find('panel').each(function() {
panel :{width: $(this).attr('width'),
height: $(this).attr('height'),
xpos: $(this).attr('xpos'),
ypos: $(this).attr('ypos')
}});// end .each()
Rewrite your code as follows:
var activity = {
title : {
text: $(xml).find('title').text(),
xpos: $(xml).find('title').attr('xpos'),
ypos: $(xml).find('title').attr('ypos')
},
rubric : {
text: $(xml).find('rubric').text(),
xpos: $(xml).find('rubric').attr('xpos'),
ypos: $(xml).find('rubric').attr('ypos')
},
panels : []
};
$(xml).find('panel').each(function() {
var data = {
panel :{
width: $(this).attr('width')
},
height: $(this).attr('height'),
xpos: $(this).attr('xpos'),
ypos: $(this).attr('ypos')
}
activity.panels.push(data);
});
EDIT
You are breaking the syntax of the object literal. You should init an array and finish the object declaration. Then iterate over your collection and fill your object's panels property with appropriate value.
EDIT
Yeah. I see what do you mean.
Here is the fiddle that iterates over your dom elements. I used the native JavaScript api. I'm not very familiar with, say, jQuery2XML.

Categories

Resources