logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
Jun 8, 2012 Posted on Jun 8, 2012 in Hints and Tips | 10 comments

Quick Tip: JavaScript Web Workers Move Hard Work to the Background

A web worker is a JS script that runs in the background, separately from other scripts, allowing us to introduce threading in our web apps. Although not part of the HTML5 spec, web workers can be used with HTML5 apps. In this Quick Tip, we’ll take a look at how to use them.


Introduction to Web Workers

In the land of HTML5 we have some very interesting APIs available. Some of them – like Web Workers – are useful for increasing performance, which is very important for both apps and games. But how do web workers… well, work?

Every instance of a web worker creates another thread, in which your JavaScript runs. You instantiate one like so:

var worker = new Worker('filename.js');

Here, ‘filename.js’ is the name of file containing your script. Because Workers are individual environments, you can’t use code embedded directly in HTML; you must use a separate file.


Communication: Sending and Receiving Data

Workers don’t have access to the page DOM or the global object, so how do they communicate with the site? It’s simple. When you want to send some data from your page to a Worker, you invoke postMessage().

This takes one parameter: data to send, which can be either a string or a JSON parsable object (which means that you can’t pass functions or circular references, or you will get a DOM_EXCEPTION). On some browsers there is a problem with objects, so it’s always better to manually parse the object with JSON.parse() so you don’t have to worry about incomplete implementations.

The same goes if you are sending data from a Worker to the page: just invoke postMessage() on self, which refers to the Worker’s global scope. (You do this inside the Worker’s script, of course).

Then, to receive the data you have to attach an onmessage event handler. There are two ways of doing that, just like with regular events for DOM elements; you can either directly assign some function to the Worker’s onmessage property, or you can use addEventListener().

// First way:
worker.onmessage = function (e) {
	console.log(e.data); // Log the data passed
}

// Second way:
worker.addEventListener('message', function (e) {
	console.log(e.data); // Log the data passed
});

It’s your choice which method to use. Either way, the function’s parameter will be an event object, and the data you sent using postMessage() will be passed via the data property of this event.


External Scripts and Libraries

Okay, but what if we have to use some external library? We don’t have access to the DOM or the global scope, so we can’t just inject the script.

Of course we don’t need to – there is a function for that. It is called importScripts() and it accepts one or more arguments: script names to load inside the scope of the Worker. You should be aware that scripts passed into this function are loaded in a random order, but they will be executed as specified and script execution will be paused until they are loaded.

importScripts('one-lib.js'); // Loads one script
importScripts('first-lib.js', 'second-lib.js', 'third-lib.js'); // Loads three scripts

You can use importScripts anywhere in your code, making it easy to create JSONP requests inside the Workers, as we will do in the following example.


Example: Workers in Action

Right, so now you probably want to see a Worker in action. Instead of showing something fairly useless, like obtaining primes or Fibonacci numbers, I’ve decided to make something that you will maybe use after a few changes.

The example script (I’ve included the Worker’s code only, the rest is easy to do) will get the last 100 Tweets from @envatoactive (we need to set the count to 121 instead of 100, as Tweeter API is sending fewer tweets than requested – don’t ask me why, I don’t know).

Here’s the code that would go inside the actual Web Worker script file:

// Helper function for processing the data
var process = function (data) {
	// Iterate through the data; we know it's an array, so it's safe
	for (var i = 0, v; v = data[i]; i++) {
		// And pass Tweet's text to the page
		self.postMessage({ text: v.text });
	}
	// After work is done, let the page know
	self.postMessage("finished");
}

// Attach event listener to handle messages
self.addEventListener('message', function (event) {
	// Check if command sent was 'start'
	// Not necessary here, but may be useful later
	if (event.data == "start") {
		// Reply to the page that we started the work
		self.postMessage("started");
		// Core of the script, get the Tweets
		// The callback parameter specifies the function to execute after the request is done
		// (We call the process() function, defined above.)
		// Count needs to be 121 because Tweeter API is sending lower amount of data than requested
		importScripts("http://twitter.com/statuses/user_timeline/envatoactive.json?callback=process&count=121");
	}
});

It should be easy to understand how this all works from the comments. This lets your app load all the tweets in the background, using a separate thread.

Now try inserting the following equivalent code, which doesn’t use web workers, into the head of an empty page instead, and note the delay. (It’s still small, but imagine if you were getting not 100 but 100,000 Tweets):

<script type="text/javascript">
	var process = function (data) {
		// Iterate through the data; we know it's an array, so it's safe
		for (var i = 0, v; v = data[i]; i++) {
			// And log Tweet's text to the console
			console.log(v.text);
		}
	}
</script>
<script src="http://twitter.com/statuses/user_timeline/envatoactive.json?callback=process&count=121"></script>

Conclusion

As you can see, web workers offer you a simple way to remove lag from your GUI and move complicated calculations or networking to separate threads.

I hope you learned something new from this article – maybe you will use Workers in your next project? If you have any questions or problems please comment below.



View full post on Activetuts+

May 15, 2012 Posted on May 15, 2012 in Hints and Tips | 10 comments

Quick Tip: Versioning Your Files With Dropbox (via Webdesigntuts+)

Ian Yates of Webdesigntuts+ has posted a great Quick Tip explaining how you can use Dropbox or Google Drive as a simple, automated version control system. It’s worth checking out for web app and game developers too, so check it out below.


Introduction

Having a version history of your graphics documents may save you from that awful moment when you realize you’ve scrubbed over a crucial stage of the design process. Thanks to Dropbox, you may already be storing versions of your work without even having noticed…

Dropbox is like a time machine. It keeps snapshots of every change in your Dropbox folder over the last 30 days.


Version History in the Cloud

You can download the video here.

Remember, both Dropbox and Google Drive will keep snapshots of your files for just 30 days, unless you upgrade your account. You can read more of what Google has to say on the matter at support.google.com, or head on over to Dropbox Help to read up on their “Pack-Rat” pro feature (which gives you indefinite history storage).


Useful Resources

  • Sign up for Dropbox if you haven’t already!
  • Sign up for Google Drive

And don’t forget, you can view all the latest articles from across the Tuts+ network at the Tuts+ Hub!



View full post on Activetuts+

Apr 27, 2012 Posted on Apr 27, 2012 in Hints and Tips | 10 comments

Quick Tip: Configuring Sublime Text 2 for Dart Coding

Sublime Text 2 is a powerful text editor, popular due to its cross-platform availability and its knack for leveraging pre-existing TextMate capabilities. Combine Sublime Text 2 with Google’s new Dart language, and power coders can be very happy.


Prerequisites

In order for this to go quickly, I’ll assume that you have some foundational knowledge. You should be familiar with the following for this tip:

  • A working knowledge of Sublime Text 2 packages. Most of this tip centers on the steps required to build our own Dart package, but if you’ve never used a snippet before you might want to back up for a second and go learn more about Sublime Text first.
  • A working knowledge of Dart will also help. We won’t really be coding any Dart in this tip, but having a few Dart files around with which to test things will help greatly.
  • We’ll be checking code out of a Subversion repository, and while I’ll feed you the command to use, hopefully this isn’t your first time using Subversion.
  • Finally, a general knowledge of your particular OS is in order. We’ll need to do a small amount of configuration and if you’re comfortable, say, modifying a .bash_profile file via the Terminal, then you’ll be fine.

If you need some prior reading material, I refer you to the following:

  • Sublime Text 2 documentation (however unofficial) is kept at sublimetext.info/docs. The pages on Packages, Syntax Definitions, and Snippets were particularly useful in the writing of this tip.
  • Dart information can be found at the official site, or by following along Activetuts’ Introduction to Dart tutorial
  • Much has been written about Subversion, not to mention a complete online book. That’s a bit more than you need, as you simply need to have Subversion installed and to checkout a single folder
  • Google will be your friend when it comes to learning more about configuring your system.

Step 1: Install Dart Editor

We won’t really be using the Dart Editor (the point of this tutorial is to use Sublime Text for Dart development, after al), but the download includes the Dart SDK, which is really what we’re after. Even if you’re a hardcore Sublime Text 2 fanatic, it’s still not a terrible idea to have the “official” Dart Editor installed and handy.

On the official Dart site, you can download the Dart Editor from the following link:

http://www.dartlang.org/docs/getting-started/editor/

Under “Step 1″ of that page, you’ll find a link to a ZIP file containing the Dart Editors. It’s around 70-100 MB, depending on your OS, so it’s not a terribly heavy download. But get it started!

The Dart Editor is based on Eclipse, so if you’ve used that you’ll be right at home with the Dart Editor. I won’t be getting into details on using it in this tutorial, but feel free to play around with it. The Activetuts+ introductory Dart tutorial (currently exclusively available through Facebook) takes you through the basic usage of the Dart Editor.

Note that if you don’t want to install the Dart Editor, you can download just the Dark SDK for your OS at this URL (it’s only 2 or 3 MB):

http://www.dartlang.org/docs/getting-started/sdk/index.html


Step 2: If You Have 64-Bit Linux

If you don’t have a 64-bit Linux installation, you can skip this step. (Yep, that includes you, Windows and Mac users; scroll down for your instructions.)

If you are on a 64-bit Linux installation, you’ll need to install a 32-bit library in order to run the Dart compiler, even if you’ve downloaded the 64-bit Dart Editor. I’m not a Linux guru by any stretch, but this worked for me, on my Ubuntu 11 installation.

Go to the Software Center and search for “lib32stdc++6″ or “GNU Standard C++ Library 32 bit”. Install it. You can continue on with the next few steps while it installs – just be sure this library has successfully installed before attempting to run the build system.

Install this library if you're running 64-bit Linux

Step 3: Download Google’s Dart TextMate Language File

The TextMate language file is hosted on Google Code here (web-based view into the repository):

http://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tools/utils/textmate/Dart.tmbundle/Syntaxes/Dart.tmLanguage

This is actually part of a larger TextMate bundle (but not that much larger), but we’re only interested in the language grammar.

Before we grab that file, create a location for it to live on your system. You’ll need to create a folder named Dart in the following location, depending on your OS:

  • Mac OS: ~/Library/Application Support/Sublime Text 2/Packages/Dart
  • Windows 7: C:\Users\Administrator\AppData\Roaming\Sublime Text 2\Packages\Dart
  • Linux: ~/.config/sublime-text-2/Packages/Dart

Then open up your command line interface and navigate to inside of that newly-created Dart folder.

Subversion doesn’t make it easy to checkout a single file, but we can export a single file. Enter this command:

svn export http://dart.googlecode.com/svn/branches/bleeding_edge/dart/tools/utils/textmate/Dart.tmbundle/Syntaxes/Dart.tmLanguage

After a moment you should have the Dart.tmLanguage file in your Dart folder.

Go ahead and try it out (you may need to restart Sublime Text). Open up a Dart file and check out the colorful syntax:

A simple Dart file in Sublime Text 2, showing off syntax highlighting
A simple Dart file in Sublime Text 2, showing off syntax highlighting

Step 4: Locate your frogc Executable

frogc is the Dart-to-JavaScript compiler. It’s a command line tool, but it’s thankfully easy to use. We’ll be using it in a Sublime Build System later to turn our Dart file(s) into JavaScript, so we don’t even need to use it on the command line anyway.

To make the Build System, we need the path to our frogc executable. This was downloaded with the Dart SDK (which you either downloaded with the Dart Editor or by itself). It will be located at dart-sdk/bin/frogc. “dart-sdk” will either be where you downloaded and unzipped the SDK by itself, or nested just inside the dart folder which also contains the Dart Editor application, which will be where you placed it.

We need a command-line-compatible path to frogc. On Mac OS, you can do this:

Open up a Terminal window and drag frogc into it. The window will contain the text of the path of the file you dropped.

For Windows:

Click in the address bar of the window. It should turn into a plain text path for the folder, which you can then copy. You’ll need to add “\frogc.bat” at the end to get the path to frogc, not just the bin folder.

If you’re on Linux, you probably already know how to do this.

Make sure the path is absolute, and readily available. Place it on your clipboard or in a scratch text file for the next step.


Step 5: Create a Dart Build System to Compile JavaScript

To make this language package really useful, we should set up a Build System, which lets us run files through a shell build command.

In Sublime Text, choose the Tools > Build System > New Build System… menu. You’ll be presented with a new file with the following default contents:

{
    "cmd": ["make"]
}

This is just a JSON object that describes a very basic build command. We’ll add much more to this to make it useful for Dart development.

With that path you determined in the last step readily available, we can edit our sublime-build file.

If you’re on Mac or Linux, change the contents of the file to:

{
    "cmd": ["/Applications/dart/dart-sdk/bin/frogc", "$file"],
    "file_regex": "^(.+\\.dart):(\\d+):(\\d+):.+\\[0m(.+)$",
    "selector": "source.dart"
}

The above is what I have on my Mac system. Where it says /Applications/dart/dart-sdk/bin/frogc, add in your own frogc path.

If you're on Windows, the file will look rather similar, but you should change the "cmd" line to:

{
    "cmd": ["cmd", "/C", "C:\\insert path here\\frogc.bat", "$file"],
    "file_regex": "^(.+\\.dart):(\\d+):(\\d+):.+\\[0m(.+)$",
    "selector": "source.dart"
}

To briefly explain what this does, the cmd property is basically just what to run on the command line. frogc is simple to use: just invoke the command and feed it a file. The $file part of that line is a variable that gets expanded automatically to the page of the current file.

On Windows, things are a little funkier by default (at least in this scenario; that's not a dig at Microsoft, I swear!). What we have will run the Windows command line (cmd) with the "don't keep the terminal window up" parameter (/C, though even the "keep the terminal window up" /K parameter doesn't show it either), and run frogc.bat, passing it the full file path. This is the quick way to get it working, but does seem to produce errors in the current build. This is probably a temporary problem, as at the time of this writing these errors are produced with the standard SDK and not the latest SDK. See the next step for an alternate route.

The file_regex line is for error reporting purposes. If a line in the output of the command matches this regular expression pattern, it's recognized as an error and pressing F4 will highlight them for you in the output panel.

Unfortunately frogc uses text-styling codes to make parts of the error message a different color and/or bold. When piped into Sublime Text, these style codes are presented as regular text, so the output can be a little hard to read, with [0m and similar codes peppered amongst the human-readable text. I'm not aware of any way around this, sadly.

The final line, selector, specifies the scope in which this Build System should take place. With this set to source.dart, Dart files should automatically choose this Build System. Sublime Text 2 knows that a ".dart" file is a, well, a Dart file thanks to the language grammar we installed.

Save this file as Dart-frogc.sublime-build in [Sublime Data]/Packages/User/Dart/


Optional Power-User Step for Windows

To avoid the aforementioned errors on Windows, and also make your build system fit more in line with the Mac and Linux versions, we can add the dart-sdk bin folder to the Windows environment, so that Sublime Text knows to look there for frogc.

To add the path, click Start, then right-click Computer, and select Properties. (Alternatively: Control Panel > System and Security > System.) Click "Advanced system settings", then on "Environment Variables."

Now, find the "path" variable, in either User Variables or System Variables (it works with either). If it doesn't exist, you can click New to create it, but if it does exist, then clicking New will overwrite it, so be careful.

Append the correct path to the end of what's already there, using a semicolon to separate it from everything else. No need to escape slashes or replace spaces with underscores or anything like that. Mine looks like:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Users\Administrator\Downloads\dart-win32-latest\dart-sdk\bin

(Scroll the above box to the right.)

That'll let you run frogc c:\whatever\source.dart from the command window, but it still won't work within Sublime Text 2. For some reason, ST2 on Windows requires you to specify the file extension in your build system file, like so:

"cmd": ["frogc.bat", "$file"]

At this point, you should have a usable build system on Windows that's less likely to break.


Step 6: Using the Build System

Go ahead and try our new Build System out. Open up a Dart file, and press F7 or Control-B (on the Mac, Command-B). "B" for Build.

You should see the output panel open up at the bottom, and if the Dart is error-free, you'll just see [Finished].

The Build System is successful

If you have errors, you'll get much more complex output. For example:

The Build System showing errors

When this happens, press F4 to move forward through the various lines of error, and Shift-F4 to move backward. The error line will highlight in the output panel, and your cursor will be placed at the line and column identified by the error.

The Build System highlighting an error

Step 7: Start Building Snippets

There are potentially many useful snippets to be added to a Dart bundle. Let me get you started by adding a snippet that creates a new method.

From the Sublime Text menu, choose Tools > New Snippet... You'll again be presented with a default file, this one in XML format. Change its contents to:

<snippet>
    <content><![CDATA[
${1:void} ${2:methodName}(${3:arguments}) {
    $0${1/void|(.+)/(?1:\n\treturn null;)/}
}
]]></content>
    <tabTrigger>method</tabTrigger>
    <scope>source.dart</scope>
</snippet>

Feel free to change the contents of the <tabTrigger> node from method to something else that you'll find more useful. This is what you type before pressing Tab in order to get the snippet.

Save the file as method.sublime-snippet (the extension is crucial; the base name is what your snippet will show up as in the menus), in the following location relative to your Sublime Text 2 Packages folder:

/Dart/method.sublime-snippet

You should already have the "Dart" folder from the installation of the language grammar file.

Now try out your new snippet (you may need to restart Sublime Text, but I think this is no longer an issue).

In a Dart file, type "method" (or whatever you specified, if you forged your own tab trigger), press Tab, and watch it expand. You can tab through the various stops, starting at the return type, then to the method name, and finally in between the parentheses if you want to add arguments. The last tab will drop you at the first line of the method.

The cool part is that if you change the return type from void, you get an automatic return null statement at the end of your method body. Naturally you'll want to adapt this to your needs, but hopefully it's a feature that saves a little typing. The magic happens in the unwieldy second line of the snippet; if you've never seen this before, then it's somewhat difficult to explain concisely, but it looks at the contents of the first tab stop (the return type) and if it's anything other than "void", it adds the return null. It might make sense if you've ever used Regular Expressions, particularly with the substitution syntax of /pattern/substitute/ found in Perl.

The field's wide open for the creation of time-saving Dart snippets. Feel free to post your snippets in the comments.


That's All

And there you have it; those of use who prefer a certain text editor over anything else can continue to do so, even with this new Dart language. Thanks for reading, and I hope you learned something about Sublime Text 2's extensibility along the way.



View full post on Activetuts+

Apr 13, 2012 Posted on Apr 13, 2012 in Hints and Tips | 10 comments

Quick Tip: Configuring TextMate for Dart Coding

Dart is a pretty cool new language that could mean a change in the way you write web applications. Google provides an Eclipse-based Dart Editor that provides a handy means to get started. But TextMate users usually find a way to bend TextMate to their will, and this Quick Tip will get you started a-bending to use Dart with TextMate.


Prerequisites

I assume you are familiar with TextMate bundles to at least the degree of what they are and that they add functionality (usually language-specific) to TextMate. I also assume you are familiar with and are capable of checking code out of a Subversion repository. Lastly, I assume you have a little Dart experience. You don’t need much, but having some Dart files around to open in TextMate will make this go much smoother.

If you’re not familiar with Dart at this point, I can point you to the official source of information: http://www.dartlang.org/. Beyond that, Activetuts+ has previously published my introductory tutorial on the language, What is Dart, and Why Should You Care?


Install Dart Editor

We won’t really be using the Dart Editor (the point of this tutorial is to use TextMate for Dart development), but the download includes the Dart SDK, which is really what we’re after. Even if you’re a hardcore TextMate fanatic (like I am), it’s still not a terrible idea to have the “official” Dart Editor installed and handy.

On the official Dart site (see the previous section), you can download the Dart Editor from the following link: http://www.dartlang.org/docs/getting-started/editor/index-macos.html

If you’re on Windows or Linux, yet are reading this tutorial despite its Mac-centric nature, you can download the Dart Editor for those platforms from the Dart Editor for Windows and Linux pages.

Under “Step 1” of that page, you’ll find a link to a ZIP file containing the Dart Editors. It’s around 40 MB, so it’s not a terribly heavy download.

The Dart Editor is based on Eclipse, so if you’ve used that you’ll be right at home with the Dart Editor. I won’t be getting into details on using it in this tutorial, but feel free to play around with it. The current Activetuts+ Facebook Fan Bonus takes you through the basic usage of the Dart Editor.

(Note that if you don’t want to install the Dart Editor, you can download just the Dark SDK for your OS at this URL (it’s only 2 or 3 MB): http://www.dartlang.org/docs/getting-started/sdk/index.html


Install frogc

frogc is the Dart-to-JavaScript compiler. It’s a command line tool, but it’s thankfully easy to use. We’ll be using it in a TextMate command later to turn our Dart file(s) into JavaScript so we can actually use our Dart code today.

Open up Terminal (found in your /Applications/Utilities/ folder). Type the following:

nano ~/.bash-profile

If you already have some PATH customizations going on, place your cursor after these lines.

Type:

export PATH=$PATH:

And then drag the bin folder, which should be located at /Applications/dart/dart-sdk/bin, into the Terminal window. If it’s not in that location, look for a dart-sdk folder in something that you downloaded (if you downloaded the SDK by itself, this should be that download, unzipped). You should end up with something like this:

export PATH=$PATH:/Applications/dart/dart-sdk/bin

To save this file, press Control-O (that’s Control, not Command), press Return to confirm the file to save, and then press Control-X to exit nano.

Almost ready; I’ve found a problem with frogc if you happen to have spaces in your file or folder names. This can be easily fixed, though. Open up frogc. It’s an executable shell script, so don’t double-click it. Instead, drag it to your TextMate icon, and you may be presented with a warning dialog but you should be able to see the short script. You don’t need to understand what this does, just change the last line from this:

$SCRIPTPATH/dart --new_gen_heap_size=128 $SCRIPTPATH/frogc.dart --libdir=$LIBPATH $@

…to this:

"$SCRIPTPATH/dart" --new_gen_heap_size=128 "$SCRIPTPATH/frogc.dart" --libdir="$LIBPATH" "$@"

Notice that basically I’ve surrounded every path with quotes, which helps avoid the space problem.


Install Google’s Dart TMBundle

You can find the .tmbundle on this Google Code page.

You can either check out the entire Dart source, which might be interesting to poke through, or you can simply check out the .tmbundle. Using the Terminal, navigate to the location in which you’d like to have the code (type cd then drag the destination folder into the Terminal window again — note that there’s a space after cd). Once Terminal is in your desired location, type this is in for a full checkout:

svn checkout http://dart.googlecode.com/svn/trunk/ dart-read-only

…or this for just the .tmbundle:

svn checkout http://dart.googlecode.com/svn/branches/bleeding_edge/dart/tools/utils/textmate/Dart.tmbundle

If you’ve checked out the entire project, you can navigate to the .tmbundle by following this path from the project root: [dart-read-only]/dart/tools/utils/textmate/Dart.tmbundle. Either way, double-click on the .tmbundle to have TextMate install it.

A lot of TextMate users like to simply check .tmbundles out directly to their bundle directory. To do this, navigate to that directory in Terminal (this should do it: cd "~/Library/Application Support/TextMate/Pristine Copy/Bundles") and then run the second svn checkout line above (the one that checks out just the .tmbundle). This way you can easily update the bundle in-place with svn up "~/Library/Application Support/TextMate/Pristine Copy/Bundles".


Write a Command to Compile Dart to JavaScript

The Google Dart Bundle is great for adding syntax support for Dart, so when you create a file ending in .dart you get colored syntax and code folding and that sort of thing. But it doesn’t include any snippets or commands. The most useful command (indeed, the first thing I thought of) is a command to compile your current Dart script with frogc for you. We’ll add one in this step.

In TextMate, open the Bundle Editor (press Command-Option-Control-B, or go to Bundles > Bundle Editor > Show Bundle Editor)

Click on the Dart entry in the left-hand list.

With the “+” button at the bottom left, choose “New Command”.

You should see a new “untitled” command appear under the Dart bundle. Rename it to “Compile with frogc”

In the large text area on the right (labeled “Command(s)”), enter the following:

frogc "$TM_FILEPATH"

Above the text area, you have the option of having the command save the file before running. This might appeal to you (it does to me; one less keystroke!). If it does, then change the “Save” option from “Nothing” to either “Current File” or “All Files in Project”.

Underneath the text area, where it says “Input,” set it to “None”.

Below that, where it says “Output,” set it to “Show as Tooltip”. This lets any output from the command show up in a tooltip near the cursor, which means if you have errors while running frogc you can see them. They’re not terribly pretty but it’s better than nothing.

Below that, where it says “Activation,”, make sure it’s set to “Key Equivalent” then put your cursor in the text field to the right. Type Command-B; this sets this command to trigger when you type that keyboard shortcut. Command-B is the TextMate idiom for a Build command if bundles have one.

Below that, where it says “Scope Selector,” type “source.dart#8221;.

Your command window should look something like this:

The completed frogc command

Close the Bundle editor window.


Step 1: Tell TextMate Where frogc is

We’ve set up Terminal so that it knows where frogc is, but unfortunately TextMate does not share that information. The easiest solution is to add the path that we added to the .bash_profile file to your Textmate preferences.

Open up TextMate’s Preferences (press Command-, or go to TextMate > Preferences…).

Click on the Advanced button at the top, then click on the Shell Variables tab.

The Shell Variables preference

If you don’t already have a PATH variable, click the “+” button and, in the first column, type PATH.

In the second column of the row that begins PATH, type the path you added to the .bash_profile (just the path, not the part that says EXPORT PATH=@PATH:). Be sure to leave the existing value intact — add a colon at the end of what’s there already, and then copy in the new path.

Close the Preferences window, and you’re ready to try it out. If you need a Dart file, you can either create a Hello World file by creating a new project with Dart Editor, or you can dig up the examples from the Dart Editor download, in the “samples” folder. Open up a Dart file in TextMate and hit Command-B; if all goes well you should have a JavaScript file next to the Dart file after a few seconds.


Step 2: Get Feedback From frogc

If you’d like to get a little fancier, you can change the code of your compile command to this:

result=`frogc "$TM_FILEPATH"`
if ["$result" == ""]; then
    echo "Compile completed"
else
    echo $result
fi

This will give you a “Compile completed” tooltip once frogc is done running, if it runs successfully. If you have errors, they’ll still show up as they did before.

One other option: if you liked the idea of automatically saving files when running the command, you might like the idea of replacing the Save command with a Save-and-Compile command. This is as simple as changing Command-B to Command-S, and making sure you’re saving the “Current File” in the command. This overrides the regular Command-S, which simply saves the current document, with the execution of this command, which saves and then compiles.

For completeness, you can create a duplicate command that saves “All Files” and has an activation key of Command-Option-S. This shortcut will override the regular Command-Option-S in TextMate, which normally saves all files in a project. Note that because you’ve set a Scope Selector, this override will only happen in Dart files, not every time you save any file.


Start Building Snippets

There are potentially many useful snippets to be added to a Dart bundle. Generally I find myself incrementally adding them as I get to know a language and discover that the existing .tmbundle doesn’t already include one. Let me get you started by adding a snippet that creates a new method.

In the Bundle Editor, make sure the Dart bundle (or an item in the Dart bundle) is selected, then choose “New Snippet” from the “+” button. Name it “method”.

In the large text area, select all the existing text and delete it. Now enter (or paste) the following:

${1:void} ${2:methodName}(${3:arguments}) {
    $0${1/void|(.+)/(?1:\n\treturn null;)/}
}

Under “Activation,” set the pop-up to “Tab Trigger” and enter method in the text field (feel free to change this).

Under “Scope Selector,” type in source.dart.

Your snippet should look like this:

The completed method snippet

Close the Bundle Editor.

Try it out. In a Dart file, type “method” (or whatever you specified, if you forged your own tab trigger), press Tab, and watch it expand. You can tab through the various stops, starting at the return type, then to the method name, and finally in between the parentheses if you want to add arguments. The last tab will drop you at the first line of the method.

The cool part is that if you change the return type from void, you get an automatic return null statement at the end of your method body. Naturally you’ll want to adapt this to your needs, but hopefully it’s a feature that saves a little typing. The magic happens in the unwieldy second line of the snippet; if you’ve never seen this before, then it’s somewhat difficult to explain concisely, but it looks at the contents of the first tab stop (the return type) and if it’s anything other than “void”, it adds the return null. It might make sense if you’ve ever used Regular Expressions, particularly with the substitution syntax of /pattern/substitute/ found in Perl.

Given that Google provides no snippets with their .tmbundle, the field’s wide open for the creation of time-saving Dart snippets. Feel free to post your snippets in the comments. We’ll compile them and see if we can get Google to incorporate them into their official bundle.


That is All

Thanks for reading! I hope you are as excited about Dart as I am. And the Dart Editor is neat and everything, but I’m a fool for TextMate. Combining Dart with my text editor of choice is something that just had to be shared.



View full post on Activetuts+

Mar 28, 2012 Posted on Mar 28, 2012 in Hints and Tips | 10 comments

Quick Tip: Create a Typewriter Text Effect Class

In this Quick Tip, we’ll create a static, re-usable ActionScript class that will produce a Typewriter effect with a single line. Read on!


Step 1: Brief Overview

We’ll split a user defined string into an array, and then add the resulting letters to a TextField one by one using the Timer class.


Step 2: Typewriter Class

Our class will be static, which means it doesn’t need to be instantiated using the new keyword. To access a static class member, use the name of the class instead of the name of an instance.

Create a new ActionScript file and write the following code:

package
{
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.events.TimerEvent;

	public final class Typewriter
	{
		/* Declare the variables and methods as static */

		private static var chars:Array; //the characters in the string
		private static var tf:TextField; //textfield to which the string will be written
		private static var timer:Timer; //pauses between writing each character
		private static var i:int = 0; //variable used to count the written characters

		public static function write(txt:String, txtField:TextField, time:Number):void
		{
			chars = txt.split(""); //split the string into an array of characters
			tf = txtField; //assign tf to the text field passed to the function
			timer = new Timer(time); //set time according to parameter

			timer.addEventListener(TimerEvent.TIMER, writeChar);
			timer.start(); //start writing function
		}

		private static function writeChar(e:TimerEvent):void
		{
			if (i < chars.length)
			{
				tf.appendText(chars[i]); //writes a char every time the function is called
				i++; //next char
			}
			if (i >= chars.length) //check whether string is complete
			{
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER, writeChar); //clear timer
				timer = null;
			}
		}
	}
}

Step 3: Usage

The usage couldn’t be easier – just add the Typewriter.as class to your project folder and use the following code:

import Typewriter;

Typewriter.write('Text to Write', targetTextfield, 50);

That’s it, test your movie and you’ll see your TextField using the Typewriter effect.


Step 4: Example

I used the class in on this example swf so you can see the effect:


Conclusion

Use this class to create your own effects!

Thank you for reading. If you’d like a more advanced version of this effect for use in your projects, take a look at Rasmus Wriedt Larsen’s Letter By Letter Animation.



View full post on Activetuts+

Page 1 of 2112345...1020...»Last »
search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Tuts+ Community Meetup in New York!
  • HTML5 Canvas Optimization: A Practical Example
  • Recreate the Cover Flow Effect Using Flash and AS3
  • Drawing Activetuts+ to a Close
  • Intro to Dart: Creating a Marquee
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Code Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
June 2013
M T W T F S S
« Jul    
 12
3456789
10111213141516
17181920212223
24252627282930
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting