Organizing Handlebars files - javascript

In this simple example...
http://plnkr.co/edit/78ObAiirrSFPcvyiBKqn
...I try to have a Handlebars template and the content that should populate it into separate files, instead of having the template inside the HTML and the content object in the js script, as in this other example:
http://embed.plnkr.co/KXdVgedRA8K95S17peuH/
And I also found this post where this guy means the same as I do (right?):
Using pre-compiled templates with Handlebars.js (jQuery Mobile environment)
I tried that (what's on the accepted answer, see the code below), but it doesn't work. I get "undefined is not a function".
On the other hand, that answer has 90 upvotes so I must be missing something somewhere. Could someone point that out to me?
Another related question: should I use AJAX to load a local file?
index.html
<script src="cities.tmpl.js"></script> <!-- compiled template -->
<script src="content.js"></script>
<script src="script.js"></script>
script.js
var template = Handlebars.templates['cities.tmpl']; // your template minus the .js
var context = data_pr.all(); // your data
var html = template(context);

Solved it, based on this post:
http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
I changed a little bit so it's easier to read (at least for me):
function getTemplate(path, callback) {
$.ajax({
url: path,
success: function(data) {
var template = Handlebars.compile(data);
if (callback) callback(template);
}
});
}
getTemplate('cities.tmpl', function(template) {
var html = template(data_pr); // data_pr = my data from content.js
document.getElementById('cities-placeholder').innerHTML = html;
});
sample code here

Related

How to use Docx.js?

i have use docx.js for generate docx file, but generaeted docx doenot open. my generated docx file output is
i have included following js file into my Html page
<script type="text/javascript" src="js/Docx/jszip.js"></script>
<!-- Include main js lib -->
<script type="text/javascript" src="js/Docx/DOCX.js"></script>
and javascript function is
function test() {
//alert("test fn call");
var doc = new DOCXjs();
doc.text('DOCX.js is a free open source library for generating Microsoft Word Documents using pure client-side JavaScript.');
//doc.text('It was developed by James Hall at Snapshot Media.');
var output = doc.output('datauri');
}
when i click button this function will be calling, and also i want to add datatable as a content of word document so how to add content using Docx.js?
Probably you are trying to use the docx.js without server, that will not work because it can't load the necessary files.
if you are executing the code on a server then edit the path of '/blank/' somewhere in the docx.js file
$.ajax({
url: '/blank/' + files[file],
complete: function(r) {
//file_data[this.url.replace(/blank_/, '')] = r.responseText;
zip.add(this.url.replace('/blank/', ''), r.responseText);
file_count_current ++;
if (file_count == file_count_current) {
doOutput();
}
}
});

untermitated string literal when using resources in razor

I have a razor code which is using resorces from resources.resx. When i use it in a function (java script), it shows error as "unterminated string literal". How do I use resources in my java script code? However in html part of my code it is able to get the actual value if #mynamespace.name
function check(arg)
{
...
var name = "#mynamespace.name";
...
}
You can't use Razor in javascript file, because javascript files are static. All you can do is use script section in your .cshtml file. You can make a walk-around following jcreamer898 post https://stackoverflow.com/a/9406739/4563955
// someFile.js
var myFunction = function(options){
// do stuff with options
};
// razorFile.cshtml
<script>
window.myFunction = new myFunction(#model.Stuff);
// If you need a whole model serialized then use...
window.myFunction = new myFunction(#Html.Raw(Json.Encode(model)));
</script>

How to read the contents of a file inside an epub using javascript

I need to read, inside a page of an epub3 book, the contents of one of the file of that same epub, being some data to process with a javascript function.
Unfortunately, Javascript prevents from loading local files for security reasons. (e.g the File API only allows loading uploaded user files).
But for me in the context of an epub3, it makes sense and I didn't find any information in the IDPF EPUB3 documentation related to this topic.
Any idea ?
OK. Let's clarify:
I have an epub3 with the following structure:
<root>
META-INF
...
OEBPS
pages
page.xhtml
data
data.xml
In page.xhtml, I want to write in Javascript something like:
<script type="text/javascript">
//pseudo code
var indata = readAsText("../data/data.xml"); // how to write that ???
var outdata = myfunction(indata);
</script>
Found the solution for ages, and realized that it had never been answered:
So answering to my own question ;-)
<script type="text/javascript">
/* Load the file using HTTP GET */
$.get( "../data/data.xml", function( indata ) {
var outdata = myfunction(indata);
}, 'text');
</script>

Load page with Ajax and load new scripts if necessary

I have a page1 which has a wrapper with articles.
<div id="wrapper">
<article>...</article>
<article>...</article>
<article>...</article>
<article>...</article>
</div>
I am loading new articles from page2 with Ajax and appending them to the wrapper
$.ajax({
url : page_to_load,
success : function (data) {
$('article',data).appendTo('#wrapper');
}
});
But some of this new articles might need specific scripts that were not loaded in page1 but would be loaded if accessed directly page2.
So the problem is some of the content in new articles breaks as they are missing those scripts.
What is the best solution? I can think of checking the new loaded page scripts and compare them with the already loaded and download the new ones, but I have no idea of how to do this.
EDIT
I noticed if I set the dataType to 'html' I cant search for the scripts, although they are there:
$('script',data)//doesn't match anything
But if I do:
console.log(data);
I can see the whole page with <html> and <script> tags
There is no problem actually, if you append HTML to the Dom then script calls will be interpreted as if the page was loaded directly, just make sure you use the same parameters as the shorthand jquery $.POST method.
I actually do this all the time and the <script src=""> are called and interpreted correctly
Just make sure you're accessing the scripts from the right scope as if the html was hardcoded on page1.
If this doesn't work, then check with the web inspector if the scripts are loaded or not.
Working solution:
$.ajax({
url : page_to_load,
success : function (data) {
// load the scripts
var dom = $(data);
dom.filter('script').each(function(){
var scriptSrc = $(this).attr('src');
if(!$('script[src="'+ scriptSrc +'"]').length && scriptSrc !== undefined) {
var script = $("<script/>");
script.attr('src', scriptSrc);
$("head").append(script);
}
});
// load the articles
$('article',data).appendTo('#wrapper');
}
});
Not sure but maybe you could add a script in the AJAX call - I'm not sure of this because I haven't tried it:
Proxy.Scripts.Add(new ScriptReference(AddVersion("/Pages/Items/SearchList/SearchList.Grid.js" )));
This workflow should work :
After every page request :
Get all the script tags in the loaded page.
Loop over the scripts
If it's not loaded yet , load it.
Here is the code snippet :
$.ajax({
url : 'http://localhost',
success : function (data) {
$('article',data).appendTo('#wrapper');
$.each($.parseHTML(data,null,true),function(){
if($(this)[0].tagName == "SCRIPT"){
var src = $(this).attr('src');
if($('script[src="'+ src +'"]').length){
$.getScript(src);
}
});
}
});
Disable async.
$.ajax({
url : page_to_load,
async: false,
success : function (data) {
$('article',data).appendTo('#wrapper');
}
});
you can use RequireJS or HeadJs library for calling js files.
RequireJS is a JavaScript file and module loader and HeadJS, a small library for Responsive Design, Feature Detections & Resource Loading
HeadJs is great and useful, try it.

JavaScript File For Each HTML File?

I have a javascript file that handles the scripting of several HTML files.
I started running into issues as everything is just written out, and nothing is called in functions (so all AJAX calls for instance are called at all pages, even though each call should only be called at one page one).
What is the best way to go about improving/fixing this? Here are the two ways that I thought of doing it:
Create a separate JS file for each HTML file
Put all JS code in functions and call each function respectively
I am leaning towards putting all my code in functions. However, when I did:
<script src="the_source">
call_function
</script>
That didn't seem to work. I put that right before where the responsible HTML was. I originally wrote it in Haml as follows:
%script{:src => "src"}
call_function
How can I get this HTML function calling working?
Or is separating them whereby each HTML file has a different JS file considered a better solution? The problem is that there is a lot of shared code between them. To solve this, I can create a different file with the shared code in objects which can be called from the other JS files as needed.
What is the cleaner approach/solution to this problem?
To call function use:
call_function();
Edited:
<script src="the_source"></script>
<script >
call_function();
</script>
where "the_source" is path to your js file
End edit
To separate the logic in every page i would just create some settings object and put there flag for cases you want to have separate:
//this code should be on every page you need your javascript file
<script src="the_source"></script>
<script>
var settings = {
mode:'doSomething1'
}
call_function(settings);
</script>
in your js file do things depending on the settings.mode value:
function call_function(settings)
{
switch(settings.mode){
case: 'doSomething1':
//code for case1
break;
case: 'doSomething2':
//code for case2
break;
default:
//code for default case
break;
}
}
This depends on your hosting plan:
If it's a dedicated or semi-dedicated server, I would prefer to have a shared JavaScript file (for performance).
If it is any other kind then separate file is faster as it distributes the load of requests in different JS files.
If you don't want to create separated files as it will be messy, I suggest to do the following:
<script src="somewhere">
var page = "<?PHP echo basename($_SERVER['PHP_SELF']); ?>";
Run_Function();
</script>
In somewhere:
function Run_function(){
switch(page){
case "1.php":
//Do Something
break;
case "2.php":
//Do Something else
break;
default:
alert("Unregistered webpage");
break;
}
Good Luck :D
EDIT:
Try up this function to get the file name from the URL:
function FileName(){
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
return filename:
}
UPDATE:
Please check this improved function of the above:
function FileName(){
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if(filename == "" || filename == "Undefined"){
filename = "index.ruby";//or any other extension
}else{
var filename = filename.replace(/%C3%84/g, "Ä");
var filename = filename2.replace(/%C3%96/g, "Ö");
var filename = filename2.replace(/%C3%9C/g, "Ü");
var filename = filename2.replace(/%C3%A4/g, "ä");
var filename = filename2.replace(/%C3%B6/g, "ö");
var filename = filename2.replace(/%C3%BC/g, "ü");
}
return filename:
}
This function might help more people and it is more flexible to use.
I would put your JS code into several different files, one for each page.
This can help your site run quicker (admittedly not by much) because the browser isn't running through tons and tons of code to find the required function.
Also, (and this is just a personal opinion) , a JS file with just a long list of short functions is quite ugly and seems less efficient.
And yeah, include an extra file with the shared code on. Try to make sure nothing is repeated unnecessarily in the files!
Good luck! :)

Categories

Resources