I am working on one old legacy ASP.NET WebForms project. It had a lot of inline JavaScript rendered from server-side. Personally I think it is a very bad practice. I think the modern world tends to use static JavaScript files and unobtrusive markup.
I don’t see an easy way to refactor that quickly so I’m improving the code gradually.
I started to use require.jswith my new scripts and…
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
If you know what require.js does and Ruby on Rails is your thing, then you have come to the right place. If not, I encourage you to read up on following topics:
Modular approach to writing JavaScript
AMD and JavaScript
Dependency management, Module Loading and Lazy Loading
Installation and Setup
Add 'requirejs-rails' gem in the Gemfile of your project. It relieves you from some manual labour.
Get rid of everything from your application.js which is located under /assets/javascripts/application.js
Now locate your application layout under views/layouts/application.html.erb
Replace your
<%= javascript_include_tag :application %>
with
<%= requirejs_include_tag :application %>
Do ‘Bundle Install’ and Restart rails server. When your server is back up and running, view page source and you should see following in your HEAD
If everything went well thus far, you should see an alert and if you are using Google Chrome, you should also see that in 'Developer Tools’, under ’Network’, require.js and then application.js loaded.
Start writing your modules
Let’s say you need an Ajax loader for your Ajax requests and you wish to write a separate module for it. Great idea. Now, let me tell you how you can write a module that can be loaded with require.js. In other words, this module that we are about to write will comply to AMD (Asynchronous module definition)
Basic module syntax:
ajaxloader.js
define([], function() { //return an object to define the “ajaxLoader" module. var ajaxLoader = { addLoader: function() { // Method }, removeLoader: function() { // Method } } return ajaxLoader; });
You define a module by using ‘define’ and it usually takes 2 arguments 1st of which is an array of it’s dependencies and 2nd is an anonymous function. You can either return a value, another function or an object literal as above.
Basic module with dependencies:
Let’s say our ajaxloader module depends on jQuery. jQuery needs to be passed as a reference. Like this
define([jQuery], function($) { //return an object to define the “ajaxLoader” module. var ajaxLoader = { addLoader: function(element) { // sample method // Perform operation on element passed // Like this console.log($(element)); }, removeLoader: function(element) { // Method // Perform operation on element passed // Like this console.log($(element)); } } return ajaxLoader; });
You must wonder, how does ‘define’ find dependancies? Well, we need to tell require.js about the location where it can find modules, dependencies.
Configure require.js
Open your application.js and let’s add jQuery as your dependency.
There’s a lot of configuration options available at http://requirejs.org/docs/api.html#config however, for now we shall focus on setting jQuery as a dependancy (jQuery is AMD compatible unlike Backbone, underscore and many other popular libraries however, SHIM config can help you our in that regard http://requirejs.org/docs/api.html#config-shim).
Explanation:
Now it’s time to tell require.js about our ajaxloader module. Follow the steps below
Add the following code in application.js right below require.confirg chunk of code
require([‘ajaxloader’], function(){ // This is will only load our ajaxloader module but no need to write anything though });
Now, let’s take a look at our module. our first string parameter in a dependency array is ‘jQuery’ and according to our require.config jquery if CDN fails will be pulled from a ‘vendor’ directory.
Order on which require.js pulls files and sticks them in the head:
require.js
application.js
jquery.min
ajaxloader.js (Loaded after jQuery because it depended on jQuery)
In closing, require.js helps you
Abstract your code without polluting the global namespace by using AMD pattern in your modules.
Manage Dependencies in a much more structured way.
As applications become larger an issue almost immediately comes up of loading the correct dependencies and keeping track of the right libraries. For one productivity application I'm creating I've found that I have so many dependencies loading that need to be in an exact particular order. Scaling this app becomes increasingly difficult. Thankfully there's Require.Js. Although I've just started to tap the potential of Require, its already paying dividends for modularizing my code and cleaning up my projects.
With Require Js one can keep track of how modules are used, the frequency of which they need to be used and what other dependencies like jQuery or Moustache need to be in place. And although its extremely powerful its implementation is easy.
The only aspect I found myself tripping up on was when to use requriea nd when to use define. These two methods allow you to utilize different dependencies.
require['underscore''], function($) {
// any dependencies that jquery needs to load will be loaded
}
define ['underscore', 'jquery', 'b' 'c'], function($) {
// you must explicitly define the dependencies that you need in order to load underscore
}
There's plenty more nuance to require.js that i'm still picking up but the basics are already very powerful.
We spent some time on the Facebook integration and there is definitely a lot going on there to greatly improve our commenting system. While researching, though, it suddenly became clear that a purchase Facebook made a while back would play to our strengths. We're now completely redeveloping the nghtclub mobile and desktop experiences to run on Parse.
Parse offers a ton of pretty slick functionality all with a much lighter coding integration. Our current version of nghtclub runs on custom built AWS web services with a MongoDB data store. While this is great, it is slowing our ability to quickly build new features. We have to bring up a new service, make sure the data is properly formatted and stored, and write all of the client-side code. Parse doesn't necessarily make this easier or better, but it makes it simpler to create new classes without writing any code. Plus utilizing their cloud code platform server-side code can run jobs and "stored procedure" type of queries all written in javascript.
Where Parse really shines is in the social integration. Our dev environment already has Facebook authentication and we'll be adding Twitter in the next day or two. We're also hoping sharing to your Facebook or Twitter account is a breeze to help spread your cool videos with the world. Oh, and to that point, we've restructured the way the app handles videos. Now it will be more like YouTube whereby each video has a unique id which can be shared and linked to quickly.
This was literally a huge re-write to migrate to the Parse platform. Since we had to touch every line of code, this seemed like the ideal time to introduce some new javascript structures to make the front-end more scalable. We're now using require.js in addition to knockout,js. While that will help to optimize the production code down into fewer requests, the big win has come from the inclusion of two plugins by Ryan Niemeyer (along with his well written articles). We're using both knockout-amd-helpers and knockout-postbox to help modularize the knockout code and introduce an easy-to-use pub/sub communication layer. Knockout is brilliant for making binding super easy, but the way that it is deployed somewhat requires a large model for a single-page application. Breaking it down isn't as easy as building a bunch of classes, especially once require.js is on the scene. Using knockout-amd-helpers made it much easier to create truly standalone modules while knockout-postbox allowed these modules to publish and subscribe to observable changes. Problem solved.
We haven't even started the migration of the mobile app to parse, but this shouldn't be too difficult. We're adding a ton of features like ratings (finally!), comments and event groupings so look for the desktop site first. We'll get a new version of the iOS app out shortly thereafter. Happy holidays and be sure to capture lots of great videos for nghtclub.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
En esos momentos cuando estas programando con RequireJS + BackboneJs y necesitas console.log para debug en firefox o chrome y te das cuenta que RequireJS no permite variables globales.
Para ello debes incluir console como una libreria de Javascript