Using Backbone.js with _.noConflict() - javascript

I'm looking to use Backbone.js with a namespaced underscore library. Does anyone know how I can tell Backbone to refer to say, underscore and not _
Thanks!
Matt

As of today (version 0.5.3) Backbone isn't ready for this in it self but it can be done:
You need to put your script tags requesting underscore.js and backbone.js first/early among your script tags, and do your _.noConflict() in a script between the underscore,backbone scripts and the rest of the script loading. Here's a schematic version:
<!DOCTYPE html>
<html>
<head>
<title>Labbo</title>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script>
var underscore = _.noConflict();
</script>
<script>
// In it's own script tag for readability
console.log('_ object: ', _);
console.log('"underscore" object: ', underscore);
var m = new Backbone.Model({});
console.log('Dummy backbone model: ', m);
</script>
<!-- Load your other scripts. From here on the '_' global isn't defined -->
<!-- any more. -->
<!-- <script src="your_other_scripts.js"></script> -->
</head>
<body>
Open Developer Tools / Firebug and check the output in the console.
</body>
</html>
(Couldn't put this on jsfiddle beacuse to demo you need control over excactly where the script tags go).

Related

How to create Backbone View in a separate js file

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.

Moving javascript into body

I am working in an ASP.NET MVC project that uses a lot of #section scripts blocks. We also use a lot of partial views. Currently, I have our global JS (global.js) rendered in the <head> element, which blocks the rest of the page from loading until it has finished loading. I want to move this JS into the body, but because my partial views are reliant on the global.js, this becomes a problem. The rendered HTML turns out to be:
<html>
<head>
<title>Page</title>
<!-- Scripts/styles here -->
</head>
<body>
<!-- Partial A -->
<div id="PartialA">Partial A</div>
<script type="text/javascript">
$(function(){
Foo.bar();
});
</script>
<script type="text/javascript" src="global.js"></script>
</body>
</html>
And global.js:
var Foo = {};
Foo.bar = function(){
console.log("I did Foo.bar()!");
}
Is there anything I can do to place my global.js just before the </body tag while still allowing the JS that uses global.js to exist higher up in the body? Maybe some sort of custom "ready" event I can subscribe to?
why not in Partial A
window.initPartialA = function () {
Foo.bar();
}
and in Global
if (window.initPartialA) {
initPartialA();
}
This is really gross, I would figure out a way of how to organize your script tags in asp rather than doing this.

Need help setting up backbone.js: Uncaught ReferenceError: Backbone is not defined

I am trying to set up a backbone driven web application but cannot get Backbone to load correctly. I get two errors when I load the required files:
-Uncaught ReferenceError: Backbone is not defined test.html: 17
-Uncaught TypeError: Cannot read property 'each' of undefined backbone.min.js: 1
I have tried multiple sources for the backbone, underscore and jquery files and am still having the same errors. Any help would be appreciated. Thanks.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="backbone-min.js"></script>
<script "text/javascript" src="jquery-2.1.1.js"></script>
<script "text/javascript" src="underscore-min.js"></script>
<script>
Person = Backbone.Model.extend({
initialize: function(){
console.log("hello world");
}
});
var person = new Person();
</script>
</body>
</html>
You must include your libraries properly to fulfill missing dependencies:
<script src="jquery-2.1.1.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
It's important to include underscore before you include backbone because underscore is a dependency of backbone.
include Backbone.js and Underscore.js(a dependency of Backbone.js)
Related introduction on backbone.
This is a common mistake with common libraries such as jQuery, wherea libraries like Bootstrap rely on components provided by an external provider.
A quick glance and I can't see anything immediately wrong, although you are missing the 'type' on your second and third script tags. When you run the page in browser, are there any errors logged out to the console, can you see the libraries being loaded fine in the network viewer too? My immediate hunch would be the source paths are wrong and so the libraries aren't being loaded.
Dependencies!!! The order matters, backbone needs jQuery and underscore
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script>
Person = Backbone.Model.extend({
initialize: function(){
console.log("hello world");
}
});
var person = new Person();
</script>
</body>

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>

Calling Js script function from external Scripts

Am trying to call a JS script from a function library in another script.
Eg. iceCreams.Js contains --->
iceCream(iceCreams){
var profit = .54
var Total = iceCreams * profits
return Total;
}
register.js contains -->
dailyTotals(wages, iceCreams){
var total = iceCream(iceCreams);
var profit = iceCreaps - wages
return wages;
}
Any help pointing me in the right direction?!
Make sure your page loads the iceCream.Js before the register.js:
<html>
...
<script type="text/javascript" src="iceCream.Js"></script>
<!-- now you can use functions in iceCream.Js in your register.js -->
<script type="text/javascript" src="register.js"></script>
....
</html>
Running the javascripts is done in client side and after rendering the full html. So, you have to add script tag for the library javascripts before consuming ones.
Just add script tag for the library before the one for register:
<script type="text/javascript" src="iceCreams.Js"></script>
<script type="text/javascript" src="register.js"></script>
Both script files must be referenced on the page they are used.
Additionally, to get IntelliSense in Visual Studio to work within the script, add the following line to the top of register.js:
/// <reference path="iceCreams.js" />

Categories

Resources