I’m porting the following code from AngularJS to React:
<div style="translate: translate({x}px, {y}px) scale({scale}) rotate({angle}deg)"}></div>
I tried:
<div style="translate: translate({this.state.x}px, {this.state.y}px) scale({this.state.scale}) rotate({this.state.angle}deg)"}></div>
It failed with Parse Error: Line X: Unexpected token }.
The best I came up with is:
<div style={{transform: "translate(" + this.state.x + "px, " + this.state.y + "px) \
scale(" + this.state.scale + ") \
rotate(" + this.state.angle + "deg)"}}></div>
That’s a lot of " + this.state.XXX + " and it’s very hard to read.
Is there a better way of doing it?
I came up with AngularJS-style micro-templates function. Usage example:
<div style={this.evalTpl("translate: translate({{x}}px, {{y}}px) scale({{scale}}) rotate({{angle}}deg)")}></div>
The implementation:
evalTpl: function(str) {
var state = this.state;
return str.replace(/{{.+?}}/g, function(name) {
name = name.slice(2, -2).trim();
var value = state[name];
if (typeof value === 'undefined' || value === null || (!value && isNaN(value))) {
throw new Error('this.state[' + JSON.stringify(name) + '] is ' + value);
}
return value;
});
}
It isn’t very good solution overall but, I think, it’s better than " + this.state.XXX + ".
How about:
format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
Then
<div style={{transform: this.getTransform()}}></div>
[...]
getTransform: function() {
var s = this.state;
return format("translate({0}px, {1}px) scale({2}) rotate({3}deg)",
s.x, s.y, s.scale, s.angle);
}
Related
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
I am using ajax to pull photos from instagram. Below is the ajax call:
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/media/search?lat=" + lat +"&lng=" + lng + "&distance=" + distance + "&access_token=" + accessToken + "",
success: function(data) {
for (var i = 0; i < 6; i++) {
$("#instagram").append("<li><a class='group' title='' href='" + data.data[i].images.standard_resolution.url +"'><img src='" + data.data[i].images.thumbnail.url +"' /></a>");
}
}
});
This works well due to the fact that the anchors title attribute is left blank. I was using title='" + data.data[i].caption.text + "' to pull the instagram caption as the anchor title. For the most part, this works, but I often get the following error: "Uncaught TypeError: Cannot read property 'text' of null"
I am assuming this is happening from one of two reasons:
A) no caption at all
B) a caption with characters that will not work as a title.
Does anyone know why this is happening, and also how I can fix this? I tried the following but it throws the same error:
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
} else {
var title = "";
}
Any ideas?
If there is no caption attached, Instagram does not return that field. Just add another null check.
if (data.data[i].caption !=null) {
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
}
} else {
var title = "";
}
for (x in data.data) {
var title_text = '';
if (data.data[x].caption != null) {
if (data.data[x].caption.text != null) {
title_text = data.data[x].caption.text;
}
} else {
title_text = "";
}
$("#instagram").append("<a target="_blank" href="' + data.data[x].link + '">" + title_text);
}
I have developed a ASP.NET MVC application with signalr to display the records on the page.
My table has five columns (jobid [int], name[varchar], lastexecutiondate[datetime],status[int],imageurl[string])
Here is my markup from view page:
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th><th>Image URL</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td>' + data[i].imageurl + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px">
</table>
</div>
</body>
And below is my code to get the data from database
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = x.GetString(4)
}).ToList();
I want to display the image instead of the URL.
You should just need to create an image tag in your JavaScript table row function:
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + data[i].imageurl + '"/></td></tr>');
}
I can think of a couple of ways to address your comment below. In code, create a helper function to do this for you:
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = GetImageUrl(x.GetString(3))
}).ToList();
private string GetImageUrl(int status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}
I don't know your code that well, so this assumes that your select is not being cast to a SQL statement (it doesn't appear that it is).
To do the same thing client side, you would implement the GetImageUrl function as a JavaScript function and to the same type of thing.
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + GetImageUrl(data[i].Status) + '"/></td></tr>');
}
function GetImageUrl(status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}
I use this AJAX jQuery plugin in our site. When I test it using IE, I'm getting this error ( Object doesn't support property or method 'handleError') that pertains to this line:
jQuery.handleError(s, xml, null, e);
I'm using 1.7.1 version of jQuery. How can I replace it?
Here's the full code
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if (window.ActiveXObject) {
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
} else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout) {
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success) s.success(data, status);
// Fire the global callback
if (s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global) jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && !--jQuery.active) jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete) s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
} else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return {
abort: function () {}
};
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script") jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json") eval("data = " + data);
// evaluate scripts within html
if (type == "html") jQuery("<div>").html(data).evalScripts();
return data;
}
})
handleError was removed from jQuery in 1.5. Are you sure it's working in firefox etc.?
See: When was handleError removed from jQuery?
For some reason the function is freezing along with firefox until it fully retrieve the stream from requested site. Is there any mechanism to prevent freezing, so it works as expected?
in XUL
<statusbarpanel id="eee_label" tooltip="eee_tooltip"
onclick="eee.retrieve_rate(event);"/>
Javascript
retrieve_rate: function(e)
{
var ajax = null;
ajax = new XMLHttpRequest();
ajax.open('GET', 'http://site.com', false);
ajax.onload = function()
{
if (ajax.status == 200)
{
var regexp = /blabla/g;
var match = regexp.exec(ajax.responseText);
while (match != null)
{
window.dump('Currency: ' + match[1] + ', Rate: '
+ match[2] + ', Change: ' + match[3] + "\n");
if(match[1] == "USD")
rate_USD = sprintf("%s:%s", match[1], match[2]);
if(match[1] == "EUR")
rate_EUR = sprintf("%s:%s", match[1], match[2]);
if(match[1] == "RUB")
rate_RUB = sprintf("%s/%s", match[1], match[2]);
match = regexp.exec(ajax.responseText);
}
var rate = document.getElementById('eee_label');
rate.label = rate_USD + " " + rate_EUR + " " + rate_RUB;
}
else
{
}
};
ajax.send();
I tried to put window.dump() right after ajax.send() and it dumped in the console also after the request is completed.
You need to make an asynchronous AJAX request by passing true as the last parameter to ajax.open.
Note that once you do that, the send function will return immediately, and any code after it will run before the request finishes.