How to create Backbone View in a separate js file - javascript

I'm trying to understand how to modularize the Backbone ToDo tutorial
Originally everything is inside the same file, but if I try to extract to another file:
var TodoView = Backbone.View.extend({
...
});
then this throws an error:
var view = new TodoView({model: todo});
**Uncaught TypeError: undefined is not a function**
It's probably due to a scope issue, but I don't know how to create a reference inside the $(function() so I can create this new object inside the main function.

Assuming that your first code part is TodoView.js,
and your second code part is app.js.
Write your html file like this,
<html>
<head>
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
// your dom
</body>
</html>
(Edited, at 2015-07-27)
sorry for my late reply.
how about this?
<html>
<head></head>
<body>
<!-- your dom -->
<script type="text/javascript" src="js/TodoView.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
In many case, most javascript codes are appended to just before </body>, so that javascript can use your dom!

You can use something like require.js to load your external files and manage dependancies.

Ok, the solution was to move the script references to the end of the body instead of inside the head tags.
I think that the reason is that TodoView.js is making use of templates that were defined in the body, and since the js file was being loaded before the body, the templates were not yet available.

Related

External file script is not loading

Iam using load() for loading external html file.
$("#header_section").load("header.html");
$("#sidemenu_section").load("side_menu.html");
Here, HTML file is loaded and css also loaded but script file is not loading in the page
<script src="js/utility.js"></script>
I tried to declare the above script file inside the head and inside the body. Both are not working.
Check your relative path to the utility.js file and make sure to load juery.js library before load utility.js file.
and finally try this,
<script type="text/javascript" src="${pageContext.request.contextPath}/js/utility.js"></script>
to load the utility.js file.
I think you forget to add jquery.min.js file. use below code.
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/utility.js"></script>
</head>
jQuery may only execute your code with the type attribute set to "text/javascript", per this bug filed a long time ago:
http://bugs.jquery.com/ticket/3733
Try this ...
<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>
The jQuery code that adds HTML to the DOM always strips out <script> tags. It runs them and then throws them away.
An exception to that behavior is when you use "$.load()" with the hack that allows you to load a fragment of a page:
$.load("http://something.com/whatever #stuff_I_want", function() { ... });
In that case, the scripts are stripped and not evaluated/run.

Handlebars Pass a string or Handlebars AST to Handlebars compile

I know its been asked many times, I have looked at the answers and not sure where I am going wrong.
I have looked at the docs on Handlebarsjs and followed a tutorial and both times I am getting the same error.
<!DOCTYPE html>
<html>
<head>
<script src="handlebars-v1.3.0.js"></script>
<script src="jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<script id="header" type="text/x-handlebars-template">
div {{ headerTitle }} div
Today is {{weekDay}}
</script>
</body>
</html>
And this is my Javascript
var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
I keep on getting the following error and i am unsure why
Uncaught Error: You must pass a string or Handlebars AST to Handlebars.compile.
You passed undefined
You are running Handlebars.compile() before theTemplateScript is loaded into the DOM. Move your test.js down below the template script and you should be good to go.
Moving the scripts to the bottom of the page also worked for me.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script id="header" type="text/x-handlebars-template">
div {{ headerTitle }} div
Today is {{weekDay}}
</script>
<script src="handlebars-v1.3.0.js"></script>
<script src="jquery.min.js"></script>
<script src="test.js"></script>
</body>
</html>
As others have said, the problem is that you are running Handlebars.compile() before the TemplateScript is loaded into the DOM.
Putting your javascript calls in $(document).ready() you make sure all the html is loaded first.
var theData = {headerTitle:"name", weekDay:"monday"}
$(document).ready(function(){
var theData = {headerTitle:"name", weekDay:"monday"}
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
});
in my case i was trying to assign some value to more deeper steps therefore, i faced the error.
Before my code was
app.use(function (req, res, next) {
res.locals.partials.weather = {}; = getWeatherData();
next();
});
and the problem was
res.locals.partials.weather
after removing the layer partial my problem was gone.
and the final code is
app.use(function (req, res, next) {
res.locals.weather = getWeatherData();
next();
});
In my case I got the same error but the issue was a typo in the template script in the html page. I had 'prouct-template' should have been 'product-template':
<script id="prouct-template" type="text/x-handlebars-template">
...
</script>
Once I fixed the typo the error went away and page loaded ok.
A bit of modification is needed in JavaScript file. I had the same issue. In my code, I called "handlebars" from Views (following explanation is with respect to views).
Include following in initialize function(init) of View :
theTemplate = Handlebars.compile(theTemplateScript);
In render write the remaining code :
var theTemplate = Handlebars.compile(theTemplateScript);
$(document.body).append(theTemplate(theData));
The correct way is to precompile the Handler, Store in file and then assign it to theTemplate.
You're using Handlebars.compile() before the template script loads. One simple trick would do the work for you. Use the defer tag in your script so that the entire body loads before the script runs in your <head> tag.
<head>
<script src="" defer> </script>
</head>

Meteor.js: <script> tag doesn't work inside <body>

A simple script tag inside the body tag doesn't seem to work. The alert doesn't get triggered in the code below:
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{>main}}
</body>
Any idea why?
Edit:
Just tried it with a fresh meteor app, no alert tag still:
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
Weird thing is when I copy paste the source of the html, made a new html page, and the alert will work.
Edit3: I deployed this app here: http://alert-in-body-test.meteor.com/
Do you get an alert box?
This question is still relevant in the current version of Meteor (version 0.5.4) so I wanted to describe how to include script at the end of the body.
To execute javascript at the end of the body, register a Handlebars helper and put the relevant code there, like this:
In client.html:
<body>
{{renderPage}}
{{afterBody}}
</body>
...
In client.js:
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('afterBody', function(name, options) {
$('body').append('AFTER BODY');
});
}
(For a great description of why this is required, see Rahul's answer to a similar question here: https://stackoverflow.com/a/14002991/219238 )
Its working for me
in onrender call this jquery
$.getScript('yours url')
It should work.
I have just pasted this inside one of my projects and it worked.
Your {{>main}} is strange for me tough. Also make sure that <body> is inside <html> tag.
Meteor is constructing the entire DOM from Javascript by rendering your page as a template -- the 'source' for your page as seen by the browser is basically:
<script type="text/javascript" src="/5a8a37bef5095c69bcd3844caf3532e1ba6d49bf.js"></script>
I can't find a definitive page stating that embedding a script tag in a template like this won't cause it to be executed, but it definitely feels against the spirit of what the framework is trying to achieve.
If the point is to achieve a clean separation of your markup and logic then why put it in the template. A better solution would be to use the meteor.startup call
Instead of looking the rendered html at developer tools, try looking the real downloaded html.
You will find a (probably) empty tag, with tons of script tags inside the .
In other words, the body of your meteor application is not the body of the final html, it's just your main template.
Instead, this ton on scripts shipped by Meteor, will load your templates.
So, your code will not run, cause it's been placed there. It's like when you manipulate DOM (with jQuery, for exemple), placing a script tag in DOM, after it's loaded. This script tag will not run.

icanhaz not finding template

To make this example as simple as possible, let's say I have the following code in home.html:
<html>
<head>
<!-- ALL DEPENDENCIES FOR ICANHAZ ARE INCLUDED ABOVE -->
<script type="text/html" id="foo" src="js_template.js"></script>
<script>ich.foo({})</script>
</head>
<body></body>
</html>
And in javascript_template.js, I have the following:
Hello world!
As it turns out, icanhaz is not detecting foo, so ich.foo({}) is throwing an error. What exactly is going on here?
ICanHaz.js does not automatically download the contents of src. This behavior can be seen on line 510 of ICH.js's source code, in which it checks for an innerHTML property of the script tag before defining the template.
You must define it inline, or use your own AJAX request. For example, embedded:
<script type="text/html" id="foo">
Hello, world
</script>
Or, if you are using jQuery, you can use AJAX to load the script:
$(function(){
$.get('js_template.js', function(res){
ich.addTemplate('foo', res);
});
});
Keep in mind, ich.foo() will not be available until the AJAX request completes.

JavaScript, load component/call method only if needed

I am searching for a way to clean my HTML views from script-tags.
Example:
(A view with a script tag)
<script type="text/javascript">
$jQuery().ready(function() {
call.a.method();
}
</script>
I would like to remove this script tag and put it into a class - this class should initizalize on the document ready event and execute the method which belongs to the called view.
How could I realize something like that? Is there some best practice?
Short version of my intention:
1.) Remove script tags from html files and put this code into some methods/functions
2.) Only call the method/function that belongs to a view if I call the view:
Example:
www.url.com/testview.html
Execute: obj.views.testview();
How could I realize something like a mapping and is it possible to identify the called file/view?
must move it in to a script file :)
something.js
JS Code:
$jQuery().ready(function() {
call.a.method();
}
html code
<script src="scripts/jquery-1.6.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="scripts/something.js" type="text/javascript" charset="utf-8"></script>

Categories

Resources