How to include more JavaScript inside Atom editor by Github? - javascript

I've been playing with snippets for Atom editor,
and see that I've learned I can include
JavaScript inside of a snippet, as my example shows.
(It inserts a TODO Comment with date)
TODO: (RAM) Fix this - 2014-11-23 20:55
HELLO
How can I include MORE JavaScript.?
For example
inside the snippet to set
var= to something
or
call a JS library
or
ask for input from user i.e. confirm();
and proceed on basis of confirm() function.
Any help would be appreciated, I looked for a long time,
but not much documentation on this. Submlime Text's snippets allowed lots of code to be inserted via Python.
Thanks
~Rob
Inside file snippets.cson
'.source.js':
'Date TODO: insert':
'prefix': 'datetd'
'body': """
TODO: (RAM) $1 - #{datetime = new Date(); datetime.getFullYear()}-#{(datetime.getMonth()+1)}-#{datetime.getDate()} #{datetime.getHours()}:#{datetime.getMinutes()}
#{"hello".toUpperCase(); }
$2
"""

Update: With the merge of atom/atom#4791, the capability of putting CoffeeScript code in CSON configuration files has been removed from Atom. The rest of the answer has been left intact for historic reference.
Actually, the syntax of the file is CoffeeScript (hence .cson as in CoffeeScript Object Notation), not JavaScript. It just so happens that you typed in JavaScript that is allowed as CoffeeScript. CoffeeScript doesn't use the var keyword, so you can assign variables like you did in your example:
datetime = new Date()
The other items, you'll probably have to get a little creative. I don't believe that the snippets package was intended to be used in this manner, which is why the lack of documentation on the "feature".

Related

amp value replace in place

I have an amp-list which loads bunch of data and I show them in their respective placeholders just nice and easy. What I intend to do is get a value and run a simple script on it. Let's think I have
<div>{{title}}</div>
where title is: 'This-is-my-title'
now I would like to replace the '-' in title, I know I could do it with javascript using title.replace(/-/g,' '), how can I do that in place?
I tried
<div>{{title.replace(/-/g,' ')}}</div>
but no luck :(
In plain javascript the following:
title = 'This-is-my-title'; title.replace(/-/g, ' ');
gives you "This is my title".
I am guessing you are using angular, in that case the text within {{ }} is not evaluated as a pure javascript expression. You could write an angular filter to apply to the expresssion (as described in Angular filter to replace all underscores to spaces ). It would probably be easier to handle this in the controller behind the template. Something like:
$scope.title = $scope.title.replace(/-/g,' ');
Looks like you are using amp-mustache. I don't think there is a way for you to use custom JavaScript in Mustache.js here, and restrictions from AMP prevent you to create some kind of function that you can call in {{}}. I would suggest processing in the backend before sending. (Also unfortunately, there are no other templates other than mustache available at this point)
There is a workaround on math using amp-bind here: AMP Mustache and Math
So probably after loading the JSON with amp-state, something like
myItems.map(entry => ({
myString: entry.myString.split('').map(c => c == '-' ? ' ' : c).join('')),
})
might work (I have not tested myself but worth a try, check whitelisted functions here: https://www.ampproject.org/es/docs/reference/components/amp-bind#white-listed-functions) but might still be a pain performance-wise (amp-bind has quite a bit overhead)
Edit: this actually looks quite promising, just found out actually amp-list with amp-bind do accept object for [src], as described in the doc (learning something new myself): https://www.ampproject.org/docs/reference/components/amp-bind
(checked amp-list source code and should work)

How to get javascript new object information from javascript from webkit?

I want to extract a new objects information name and arguments into a HTML page.
Such as
<script>
var a = new g(10,20);
</script>
I need to print :
new object g with arguments 10,20
I am newbie to Webkit.
Initially I thought just add a printf statement in the javascriptcore. I added some printf statements to
JavaScriptCore/runtime/FunctionConstructor.cpp ,ObjectConstructor.cpp .
But didn't get right result .
I googled but there is few tutorials about javascriptcore.
I hope some expert can point me in the right direction .
I'm not sure which version of WebKit are you hacking with, so my solution may not work.
I suggest you to add logging statements in Interpreter.cpp, inside the block of DEFINE_OPCODE(op_construct).

Conditional Compilation is turned off in Razor?

I've got a c# foreach loop that Is outputting some javascript to initialize some progress bars on my razor view.
#foreach (var item3 in Model)
{
#:$("#campaignMeter-#item3.ID").wijprogressbar({ value: #((item3.TotalRedeemed / item3.TotalSold) * 100), fillDirection: "east" });
}
The problem I'm having is visual studio is reporting "Conditional Compilation is Turned Off" on the foreach loop, and the small calculation for value is always coming out as 0, despite TotalRedeemed and TotalSold having values. Am I using the #: operator properly? Thanks for your help.
I've tried both suggestions so far and this is what I currently have:
#foreach (var item3 in Model)
{
var percentage = (item3.TotalRedeemed / item3.TotalSold) * 100;
<text>$("#campaignMeter-#item3.ID").wijprogressbar({ value: #percentage, fillDirection: "east" });</text>
}
percentage is coming out as 0, but TotalRedeemed and TotalSold have values, as they are printed on the view before this is called. Is there a way to set a break point on my view to see what percentage is before its printed?
Timmi4sa - I agree, there isn't much of an answer as to why we are getting this error. I finally got a step closer to understanding it all so I thought i would share.
Conditional Compilation is defined my MS as this:
Conditional compilation enables JScript to use new language features
without sacrificing compatibility with older versions that do not
support the features. Some typical uses for conditional compilation
include using new features in JScript, embedding debugging support
into a script, and tracing code execution.
From what I can tell, we are really talking about a feature of VS. My current guess is this: VS lets you debug JS, but it has to know what the JS is in order to debug it. By default Conditional Compilation is off - I am guessing that there is some additional overhead involved. What we are doing when we are using #Model... in JS is doing exactly what the warning states (more or less) - creating conditional JS. The JS ends up being different things depending on the value of our C#/VB variables.
According to MS the solution is to turn Conditional Compilation on as mentioned above via the statement:
/*#cc_on #*/
While I tend to be a bit anal and prefer to avoid warnings, this may be one I just simply ignore (unless someone can educate me further as to why this is a bad idea).
If you really want the error to go away and do not like the Conditional Compilation flag, you can wrap the C#/VB code call in double quotes like below. But this feels dirty and only works because JS is loosely typed... (well with numeric types anyway, strings shouldn't have a problem... regardless, this feels hacky)
"#Model.Items.Count()"
Edit: I went and did a little more research... I like the idea of CC even less after skimming this article: http://www.javascriptkit.com/javatutors/conditionalcompile.shtml. I think I will just be ignoring this warning.
I hope that helps explain away some of the mystery.
EDIT :
Another option is to throw a HiddenFor down on the form, give it an Id and then populate a JS variable from that field (jQuery makes this pretty easy). This is what I ended up doing for the time being. It eliminates warnings and I often want to compare the JS variable back to the original VMC field anyway. For those of you who need it:
#* Somewhere in your form - assuming a strongly typed view *#
#Html.HiddenFor(x => x.YourField, new { id = "SomethingMeaningful" })
// and then in your JS
$(document).ready(function(){
...
var jsYourField = $("#SomethingMeaningful").val();
...
});
Please note that JS variable and MVC variables do not always 'line up' exactly right so you may need to do some casting or additional work when you copy the variable value into your JS.
Add /*#cc_on #*/ in your code.
Update: Found out why they could be 0:
item3.TotalRedeemed and item3.TotalSold need to be float or double. If they are int, it comes out to 0.
Try this:
#foreach (var item3 in Model)
{
<text>$("#campaignMeter-#item3.ID").wijprogressbar({
value: #((item2.TotalRedeemed / item2.TotalSold) * 100),
fillDirection: "east"
});</text>
}
But a better approach would be to perform this calculation on a view model property, so that your view looks like this:
#foreach (var item in Model)
{
<text>$('#campaignMeter-#(item.ID)').wijprogressbar({
value: #item.SoldPercentage,
fillDirection: "east"
});</text>
}
I thought I would share what worked for me,
I had this same issue : System.Web.HttpCompileException (0x80004005)
below the exception I get: The name 'Url' does not exist
When I looked at the View I noticed the only place that was using Url was the razor code #Url.
This post talked about the references to razor and MVC.
When i looked in the Views folder in the solution there was a web.config file that contained all the references however it was renamed web.src.config. As soon as I changed it to web.config I was up and running again.

ASP.NET inline server tags

I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.
So I have code like this in my .aspx file:
function EditRelationship() {
var projects=<%= GetProjectsForEditRelationship() %>;
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
var rels=<%= GetRelationshipsForEditRelationship() %>;
// etc
}
Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.
I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).
So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.
If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?
Create a ASP:HiddenField control, set its ClientIdMode to "Static"
Assign the value of GetRelationshipsForEditRelationship() to this field on page load
In your javascript, read the value from the hidden field instead, I assume you know how to do this.
It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)
You could do this from your page in the code-behind
ClientScript.RegisterArrayDeclaration("projects", "1, 2, 3, 4");
or to construct something like JSON you could write it out
ClientScript.RegisterClientScriptBlock(GetType(), "JSONDeclarations", "your json stuff");
UPDATE Based on my comment
<script id="declaration" type="text/javascript">
var projects=<%= GetProjectsForEditRelationship() %>;
var rels=<%= GetRelationshipsForEditRelationship() %>;
</script>
<script type="text/javascript">
function EditRelationship() {
// fill in the projects list
$('#erProjectsSelect').empty();
for(var i in projects)
$('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');
}
</script>
I don't have VS2008 installed to test with, so take this with a grain of salt, but have you tried something like this?
var projects = (<%= GetProjectsForEditRelationship() %>);
Something like that might trick the JavaScript parser into ignoring the content of your expression.
For what it's worth, VS2010 correctly parses and highlights your original code snippet.
Is it an option to move this to VS2010? I just copied and pasted your code and the IDE interpreted it correctly.
The best solution is to put javascript in a separate file and avoid this entirely. For this particular function, you're doing server-side work. Why not build the list of options that you intend to add dynamically in codebehind, put them in a hidden div, and then just have jQuery add them from the already-rendered HTML?
If you have a situation where you really want to dynamically create a lot javascript this way, consider using ScriptManager in codebehind to set up the variables you'll need as scripts and register them, then your inline script won't need to escape
ScriptManager.RegisterClientScript("projects = " + GetProductsForEditRelationship());
(Basically, that is not the complete syntax, which is context dependent). Then refer to "projects" in your function.
(edit)
A little cleaner way to do this on a larger scale, set up everything you need like this in codebehind:
string script = "var servervars = {" +
"GetProductsForEditRelationship: " + GetProductsForEditRelationship() +
"GetRelationshipsForEditRelationship: " + GetRelationshipsForEditRelationship() +
"}"
and refer to everything like:
servervars.GetProductsForEditRelationship
If you do this a lot, of course, you can create a class to automate the construction of the script.

How do I relate a UIWebView javascript exception's sourceId to a source file?

Short question: What does an exception's "sourceID" refer to, and how can I link it to the relevant source string/file?
Longer story:
I am running Javascript code in an iPhone native app through [UIWebView stringByEvaluatingJavaScriptFromString:]. To help development, and later check user-provided code, I use the following function to safely run any code:
// Inside #implementation MyJS
- (NSString *)runJS:(NSString *)js {
// Do some escaping on 'js' to make it look like a string literal.
js = escape(js);
NSString *result =
[webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"try { JSON.stringify(eval(\"%#\")); } except (e) { JSON.stringify(e); }", js]
];
return result;
}
If all goes well, [MyJS runJS:js] runs fine and returns a JSON string containing the result of the evaluation of the last statement in the 'js' code.
Now if bad things happen during the evaluation, I get a JSONified exception object. For example, in case of a syntax error in the 'js' code, I get something like this:
{"message":"Parse error","line":1,"sourceId":26121296}
Which is already quite useful to track problems...
However, as I run multiple strings through runJS:, I would like to be able to pinpoint which one caused the exception (because a runtime error could come from a function that was created in a previous javascript code string). This "sourceId" property looks interesting, but I cannot find what it points to. It looks like a pointer address (similar value as pointers to other objects), but it doesn't match with any of the strings I've passed to the evaluator. How can I make this link?
For bonus points: Is there any documentation available about the UIWebView-specific javascript environment, like this exception object? The Safari Web Content Guide is nice, but doesn't go into this kind of details.
Worst-case solution:
Inside each js string being evaluated, add some code that throws an exception, catches it, extracts the sourceId and somehow exposes it so that the runJS: method can keep a record of which sourceId goes with which string.
(Hopefully someone will find a better way and help bury this ugly answer!)

Categories

Resources