Author Archives: admin

GIT: submodules

[Fuente: http://git-scm.com/book/en/v2/Git-Tools-Submodules]

Submodules

It often happens that while working on one project, you need to use another project from within it. Perhaps it’s a library that a third party developed or that you’re developing separately and using in multiple parent projects. A common issue arises in these scenarios: you want to be able to treat the two projects as separate yet still be able to use one from within the other.

Here’s an example. Suppose you’re developing a web site and creating Atom feeds. Instead of writing your own Atom-generating code, you decide to use a library. You’re likely to have to either include this code from a shared library like a CPAN install or Ruby gem, or copy the source code into your own project tree. The issue with including the library is that it’s difficult to customize the library in any way and often more difficult to deploy it, because you need to make sure every client has that library available. The issue with vendoring the code into your own project is that any custom changes you make are difficult to merge when upstream changes become available.

Git addresses this issue using submodules. Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate.

Starting with Submodules

We’ll walk through developing a simple project that has been split up into a main project and a few sub-projects.

Let’s start by adding an existing Git repository as a submodule of the repository that we’re working on. To add a new submodule you use the git submodule add command with the URL of the project you would like to start tracking. In this example, we’ll add a library called “DbConnector”.

$ git submodule add https://github.com/chaconinc/DbConnector
Cloning into 'DbConnector'...
remote: Counting objects: 11, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 11 (delta 0), reused 11 (delta 0)
Unpacking objects: 100% (11/11), done.
Checking connectivity... done.

By default, submodules will add the subproject into a directory named the same as the repository, in this case “DbConnector”. You can add a different path at the end of the command if you want it to go elsewhere.

If you run git status at this point, you’ll notice a few things.

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	new file:   .gitmodules
	new file:   DbConnector

First you should notice the new .gitmodules file. This is a configuration file that stores the mapping between the project’s URL and the local subdirectory you’ve pulled it into:

$ cat .gitmodules
[submodule "DbConnector"]
	path = DbConnector
	url = https://github.com/chaconinc/DbConnector

If you have multiple submodules, you’ll have multiple entries in this file. It’s important to note that this file is version-controlled with your other files, like your .gitignore file. It’s pushed and pulled with the rest of your project. This is how other people who clone this project know where to get the submodule projects from.

Since the URL in the .gitmodules file is what other people will first try to clone/fetch from, make sure to use a URL that they can access if possible. For example, if you use a different URL to push to than others would to pull from, use the one that others have access to. You can overwrite this value locally with git config submodule.DbConnector.url PRIVATE_URL for your own use.

The other listing in the git status output is the project folder entry. If you run git diff on that, you see something interesting:

$ git diff --cached DbConnector
diff --git a/DbConnector b/DbConnector
new file mode 160000
index 0000000..c3f01dc
--- /dev/null
+++ b/DbConnector
@@ -0,0 +1 @@
+Subproject commit c3f01dc8862123d317dd46284b05b6892c7b29bc

Although DbConnector is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.

If you want a little nicer diff output, you can pass the --submodule option to git diff.

$ git diff --cached --submodule
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..71fc376
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "DbConnector"]
+       path = DbConnector
+       url = https://github.com/chaconinc/DbConnector
Submodule DbConnector 0000000...c3f01dc (new submodule)

When you commit, you see something like this:

$ git commit -am 'added DbConnector module'
[master fb9093c] added DbConnector module
 2 files changed, 4 insertions(+)
 create mode 100644 .gitmodules
 create mode 160000 DbConnector

Notice the 160000 mode for the DbConnector entry. That is a special mode in Git that basically means you’re recording a commit as a directory entry rather than a subdirectory or a file.

Facebook SDK API

Fuente: https://developers.facebook.com/docs/javascript/quickstart/v2.3

Quickstart: Facebook SDK for JavaScript

The Facebook SDK for JavaScript provides a rich set of client-side functionality that:

  • Enables you to use the Like Button and other Social Plugins on your site.
  • Enables you to use Facebook Login to lower the barrier for people to sign up on your site.
  • Makes it easy to call into Facebook’s Graph API.
  • Launch Dialogs that let people perform various actions like sharing stories.
  • Facilitates communication when you’re building a game or an app tab on Facebook.

The SDK, social plugins and dialogs work on both desktop and mobile web browsers.

This quickstart will show you how to setup the SDK and get it to make some basic Graph API calls. If you don’t want to setup just yet, you can use our JavaScript test console to use all of the SDK methods, and explore some examples (you can skip the setup steps, but the rest of this quickstart can be tested in the console).

Basic Setup

The Facebook SDK for JavaScript doesn’t have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.

The following snippet of code will give the basic version of the SDK where the options are set to their most common defaults. You should insert it directly after the opening <body> tag on each page you want to load it:

    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : 'your-app-id',
          xfbml      : true,
          version    : 'v2.3'
        });
      };

      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
    </script>

This code will load and initialize the SDK. You must replace the value in your-app-id with the ID of your own Facebook App. You can find this ID using the App Dashboard.

Advanced Setup

As mentioned, the code above uses the common defaults for the options available when initializing the SDK. You can customize some of these options, if useful.

Changing SDK Language

In the basic setup snippet, the en_US version of the SDK is initialized, which means that all of the Facebook-generated buttons and plugins used on your site will be in US English. (However, pop-up dialogs generated by Facebook like the Login Dialog will be in the language the person has chosen on Facebook, even if they differ from what you’ve selected.) You can change this language by changing the js.src value in the snippet. Take a look at Localization to see the different locales that can be used. For example, if your site is in Spanish, using the following code to load the SDK will cause all Social Plugins to be rendered in Spanish.

    <script>
      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) return;
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/es_LA/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
    </script> 

Login Status Check

If you set status to true in the FB.init() call, the SDK will attempt to get info about the current user immediately after init. Doing this can reduce the time it takes to check for the state of a logged in user if you’re using Facebook Login, but isn’t useful for pages that only have social plugins on them.

You can use FB.getLoginStatus to get a person’s login state. Read on for more about using Facebook Login with the JavaScript SDK.

Disabling XFBML Parsing

With xfbml set to true, the SDK will parse your page’s DOM to find and initialize any social plugins that have been added using XFBML. If you’re not using social plugins on the page, setting xfbml to false will improve page load times. You can find out more about this by looking at Social Plugins.

Triggering Code when the SDK loads

The function assigned to window.fbAsyncInit is run as soon as the SDK has completed loading. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. Any kind of JavaScript can be used here, but any SDK functions must be called afterFB.init.

Debugging

To improve performance, the JavaScript SDK is loaded minified. You can also load a debug version of the JavaScript SDK that includes more logging and stricter argument checking as well as being non-minified. To do so, change the js.src value in your loading code to this:

js.src = "//connect.facebook.net/en_US/sdk/debug.js";

More Initialization Options

The reference doc for the FB.init function provides a full list of available initialization options.

Using the SDK to add Social Plugins

Now that you’ve got the SDK setup, we can use it to perform a few common tasks. Social Plugins such as the Like Button and Comments Plugin can be inserted into HTML pages using the JavaScript SDK.

Let’s try adding a Like button, just copy and paste the line of code below anywhere inside the <body> of your page:

<div
  class="fb-like"
  data-send="true"
  data-width="450"
  data-show-faces="true">
</div>

Reload your page, and you should see a Like button on it.

Using the SDK to trigger a Share dialog

The Share Dialog allows someone using a page to post a link to their timeline, or create an Open Graph story. Dialogs displayed using the JavaScript SDK are automatically formatted for the context in which they are loaded – mobile web, or desktop web.

Here we’ll show you how the FB.ui() method of the SDK can be used to invoke a really basic Share dialog. Add this snippet after the FB.init() call in the basic setup code:

FB.ui(
 {
  method: 'share',
  href: 'https://developers.facebook.com/docs/'
}, function(response){});

Now when you reload your page, you’ll see a Share dialog appear over the top of the page. Let’s add a few extra parameters to the FB.ui call in order to make the Share dialog make a more complex call to publish an Open Graph action:

    FB.ui({
     method: 'share_open_graph',
     action_type: 'og.likes',
     action_properties: JSON.stringify({
      object:'https://developers.facebook.com/docs/',
     })
    }, function(response){});

Now when you reload your page, you’ll see a Share dialog again, but this time with a preview of the Open Graph story. Once the dialog has been closed, either by posting the story or by cancelling, the response function will be triggered.

Read the FB.ui reference doc to see a full list of parameters that can be used, and the structure of the response object.

Using the SDK for Facebook Login

Facebook Login allows users to register or sign in to your app with their Facebook identity.

We have a full guide on how to use the JS SDK to implement Facebook Login. But for now, let’s just use some basic sample code, so you can see how it works. Insert the following after your original FB.init call:

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    console.log('Logged in.');
  }
  else {
    FB.login();
  }
});

Read the Login guide to learn exactly what is happening here, but when you reload your page you should be prompted with the Login dialog for you app, if you haven’t already granted it permission.

Using the SDK to call the Graph API

To read or write data to the Graph API, you’ll use the JS SDK’s FB.api() method. The version parameter in the FB.init call is used to determine which Graph API version is used.

We have another quickstart guide for the Graph API, however here we’ll show you how the FB.api() method can publish a story on your behalf.

First, we need to get publish_actions permission in order to make publishing API calls. So add a line after FB.init like this:

FB.login(function(){}, {scope: 'publish_actions'});

This will trigger a login dialog that’ll request the relevant permissions. Next, now that your app can, let’s make the API call to publish. Add the API code into the response function of the FB.login call you added above:

FB.login(function(){
 FB.api('/me/feed', 'post', {message: 'Hello, world!'});
}, {scope: 'publish_actions'});

Now, when you reload your page, you’ll be asked for permissions (if you haven’t granted them already) and then a status message will be posted to your profile:

Congratulations, you’ve learned how to use the JavaScript to perform a number of common tasks. Dig deeper into the guides linked in each section to learn more about specific methods, or other parts of Facebook Platform.
[Fuente : https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.3]

Facebook Login for the Web with the JavaScript SDK

Facebook apps can use one of several login flows, depending on the target device and the project. This guide takes you step-by-step through the login flow for web apps. The steps in this guide use Facebook’s JavaScript SDK, which is the recommended method to add Facebook Login to your website.

If for some reason you can’t use our JavaScript SDK you can also implement login without it. We’ve build a separate guide to follow if you need to implement login manually.

Quickstart

Later in this doc we will guide you through the login flow step-by-step and explain each step clearly – this will help you if you are trying to integrate Facebook Login into an existing login system, or just to integrate it with any server-side code you’re running. But before we do that, it’s worth showing how little code is required to implement login in a web application using the JavaScript SDK.

You will need a Facebook App ID before you start using the SDK, which you can create and retrieve on the App Dashboard. You’ll also need somewhere to host HTML files. If you don’t have hosting, you can get set up quickly with Parse.

This code will load and initialize the JavaScript SDK in your HTML page. Use your app ID where indicated.

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
  FB.init({
    appId      : '{your-app-id}',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2' // use version 2.2
  });

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });

  };

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }
</script>

<!--
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

</body>
</html>

Now you can test your app by going to the URL where you uploaded this HTML. Open your JavaScript console, and you’ll see the testAPI() function display a message with your name in the console log.

Congratulations, at this stage you’ve actually built a really basic page with Facebook Login. You can use this as the starting point for your own app, but it will be useful to read on and understand what is happening in the code above.
vcx
vcx
vcxv
cxv
cxv
cxv
cxvcx
vcx
vcx
vcx

AngularJS: Modules

[Fuente: https://docs.angularjs.org/guide/module]

What is a Module?

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.

Why?

Most applications have a main method that instantiates and wires together the different parts of the application.Angular apps don’t have a main method. Instead modules declaratively specify how an application should be bootstrapped. There are several advantages to this approach:

  • The declarative process is easier to understand.
  • You can package code as reusable modules.
  • The modules can be loaded in any order (or even in parallel) because modules delay execution.
  • Unit tests only have to load relevant modules, which keeps them fast.
  • End-to-end tests can use modules to override configuration.

The Basics

I’m in a hurry. How do I get a Hello World module working?

index.html

<div ng-app="myApp">
  <div>
    {{ 'World' | greet }}
  </div>
</div>

scripts.js

// declare a module
var myAppModule = angular.module('myApp', []);

// configure the module.
// in this example we will create a greeting filter
myAppModule.filter('greet', function() {
 return function(name) {
    return 'Hello, ' + name + '!';
  };
});

protractor.js

it('should add Hello to the name', function() {
  expect(element(by.binding("'World' | greet")).getText()).toEqual('Hello, World!');
});

sd
sd
sds
ds
ds
dsd
sd
sd
sds
d
sds
ds
ds
dsd

AngularJS: Directive resolve dependencies

If we want to wait for some server data for directive loading this is the pattern:

angular.module('busuuApp.translations')
    .directive('trs', ['trs','$http', '$q', 'wordbee', function(trs,$http, $q,wordbee,wordbeeStrings) {

  'use strict';

  var translateArgs = function(str) {
    try {
      if (str[0] != '"' && str[0] != "'") {
        return trs.call(null, str);
      } else {
        // Strips the " or ' on the start and end
        // Used to be eval("trs(" + str + ")");
        return trs(str.slice(1, str.length-1));
      }
    } catch (err) {
      $log.error('Reference error, trs directive shouldn\'t have dynamic vars: ' + args);
      throw err;
    }
  };

  //store the data so you don't load it twice.
  var directiveData,
  //declare a variable for you promise.
      dataPromise;

  //set up a promise that will be used to load the data
  function loadData(){

    //if we already have a promise, just return that
    //so it doesn't run twice.
    if(dataPromise) {
      return dataPromise;
    }

    var deferred = $q.defer();
    dataPromise = deferred.promise;

    if(!_.isEmpty(wordbeeStrings)) {
      //if we already have data, return that.
      deferred.resolve(directiveData);
    } else {
      console.log("TRS directive loadlanguage");
      wordbee.loadLanguage(interfaceLanguage)
                  .then(function(data) {
                    directiveData = data;
                    wordbeeStrings = directiveData;
                    _.each(wordbeeStrings, function (val, key) {

                      val = val.replace(/&lt;/g, '<');

                      val = val.replace(/&gt;/g, '>');

                      wordbeeStrings[key] = val;

                    });


                    console.log("trs directive Language loaded!!!");
                    deferred.resolve(directiveData);
                  });
    }
    return dataPromise;
  }

  return {
    restrict: 'EA',
    scope: false,
    link: function(scope, elm, attrs) {
      //load the data, or check if it's loaded and apply it.
      loadData().then(function(data) {
        //success! set your scope values and
        // do whatever dom/plugin stuff you need to do here.
        // an $apply() may be necessary in some cases.
        //console.log("TRS directive --> ",attrs);
        if (attrs.hasOwnProperty('trs')) {
          elm.html(translateArgs(attrs.trs));
        } else {
          // otherwise we use <trs> </trs> syntax
          elm.replaceWith(translateArgs(elm.text()));
        }
      }, function() {
        //failure! update something to show failure.
        // again, $apply() may be necessary.
        scope.data = 'ERROR: failed to load data.';
      });
    }
  };
}]);

AngularJS UI router

[Fuente: https://github.com/angular-ui/ui-router]

The de-facto solution to flexible routing with nested views

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

States are bound to namednested and parallel views, allowing you to powerfully manage your application’s interface.

Check out the sample app: http://angular-ui.github.io/ui-router/sample/

Note: UI-Router is under active development. As such, while this library is well-tested, the API may change. Consider using it in production applications only if you’re comfortable following a changelog and updating your usage accordingly.

Get Started

(1) Get UI-Router in one of the following ways:

  • clone & build this repository
  • download the release (or minified)
  • via Bower: by running $ bower install angular-ui-router from your console
  • or via npm: by running $ npm install angular-ui-router from your console
  • or via Component: by running $ component install angular-ui/ui-router from your console

(2) Include angular-ui-router.js (or angular-ui-router.min.js) in your index.html, after including Angular itself (For Component users: ignore this step)

(3) Add 'ui.router' to your main module’s list of dependencies (For Component users: replace'ui.router' with require('angular-ui-router'))

When you’re done, your setup should look similar to the following:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="js/angular-ui-router.min.js"></script>
    <script>
        var myApp = angular.module('myApp', ['ui.router']);
        // For Component users, it should look like this:
        // var myApp = angular.module('myApp', [require('angular-ui-router')]);
    </script>
    ...
</head>
<body>
    ...
</body>
</html>

Nested States & Views

The majority of UI-Router’s power is in its ability to nest states & views.

(1) First, follow the setup instructions detailed above.

(2) Then, add a ui-view directive to the <body /> of your app.

<!-- index.html -->
<body>
    <div ui-view></div>
    <!-- We'll also add some navigation: -->
    <a ui-sref="state1">State 1</a>
    <a ui-sref="state2">State 2</a>
</body>

(3) You’ll notice we also added some links with ui-sref directives. In addition to managing state transitions, this directive auto-generates the href attribute of the <a /> element it’s attached to, if the corresponding state has a URL. Next we’ll add some templates. These will plug into the ui-view within index.html. Notice that they have their own ui-view as well! That is the key to nesting states and views.

<!-- partials/state1.html -->
<h1>State 1</h1>
<hr/>
<a ui-sref="state1.list">Show List</a>
<div ui-view></div>
<!-- partials/state2.html -->
<h1>State 2</h1>
<hr/>
<a ui-sref="state2.list">Show List</a>
<div ui-view></div>

(4) Next, we’ll add some child templates. These will get plugged into the ui-view of their parent state templates.

<!-- partials/state1.list.html -->
<h3>List of State 1 Items</h3>
<ul>
  <li ng-repeat="item in items">{{ item }}</li>
</ul>

5) Finally, we’ll wire it all up with $stateProvider. Set up your states in the module config, as in the following:

myApp.config(function($stateProvider, $urlRouterProvider) {
  //
  // For any unmatched url, redirect to /state1
  $urlRouterProvider.otherwise("/state1");
  //
  // Now set up the states
  $stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "partials/state1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html"
    })
    .state('state2.list', {
      url: "/list",
      templateUrl: "partials/state2.list.html",
      controller: function($scope) {
        $scope.things = ["A", "Set", "Of", "Things"];
      }
    });
});

(6) See this quick start example in action.

Go to Quick Start Plunker for Nested States & Views

(7) This only scratches the surface

Dive Deeper!

er
errw
rewr
ewr
ewr
ewr
ewr
ewrew
rew
rwer
ew
rwer
ewr

React: A javascript library for building user interfaces

[Fuente: http://facebook.github.io/react/index.html]

JUST THE UI

Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.

VIRTUAL DOM

React uses a virtual DOM diff implementation for ultra-high performance. It can also render on the server using Node.js — no heavy browser DOM required.

DATA FLOW

React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding.

Getting Started

JSFiddle

The easiest way to start hacking on React is using the following JSFiddle Hello World examples:

Starter Kit

Download the starter kit to get started.

In the root directory of the starter kit, create a helloworld.html with the following contents.

<!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/jsx">
      React.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>
  </body>
</html>

The XML syntax inside of JavaScript is called JSX; check out the JSX syntax to learn more about it. In order to translate it to vanilla JavaScript we use <script type="text/jsx"> and include JSXTransformer.js to actually perform the transformation in the browser.

Separate File

Your React JSX code can live in a separate file. Create the following src/helloworld.js.

React.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

Then reference it from helloworld.html:

<script type="text/jsx" src="src/helloworld.js"></script>

Offline Transform

First install the command-line tools (requires npm):

npm install -g react-tools

Then, translate your src/helloworld.js file to plain JavaScript:

jsx --watch src/ build/

The file build/helloworld.js is autogenerated whenever you make a change.

React.render(
  React.createElement('h1', null, 'Hello, world!'),
  document.getElementById('example')
);

Update your HTML file as below:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <!-- No need for JSXTransformer! -->
  </head>
  <body>
    <div id="example"></div>
    <script src="build/helloworld.js"></script>
  </body>
</html>

Want CommonJS?

If you want to use React with browserifywebpack, or another CommonJS-compatible module system, just use the react npm package. In addition, the jsx build tool can be integrated into most packaging systems (not just CommonJS) quite easily.

Next Steps

Check out the tutorial and the other examples in the starter kit’s examples directory to learn more.

We also have a wiki where the community contributes with workflows, UI-components, routing, data management etc.

Good luck, and welcome!

A Simple Component

React components implement a render() method that takes input data and returns what to display. This example uses an XML-like syntax called JSX. Input data that is passed into the component can be accessed by render() via this.props.

JSX is optional and not required to use React. Try clicking on “Compiled JS” to see the raw JavaScript code produced by the JSX compiler.

This code displays “Hello John”:

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

A Stateful Component

In addition to taking input data (accessed via this.props), a component can maintain internal state data (accessed via this.state). When a component’s state data changes, the rendered markup will be updated by re-invoking render().

var Timer = React.createClass({
  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  componentWillUnmount: function() {
    clearInterval(this.interval);
  },
  render: function() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
});

React.render(<Timer />, mountNode);

An Application

Using props and state, we can put together a small Todo application. This example uses state to track the current list of items as well as the text that the user has entered. Although event handlers appear to be rendered inline, they will be collected and implemented using event delegation.

var TodoList = React.createClass({
  render: function() {
    var createItem = function(itemText) {
      return <li>{itemText}</li>;
    };
    return <ul>{this.props.items.map(createItem)}</ul>;
  }
});
var TodoApp = React.createClass({
  getInitialState: function() {
    return {items: [], text: ''};
  },
  onChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.text]);
    var nextText = '';
    this.setState({items: nextItems, text: nextText});
  },
  render: function() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.onChange} value={this.state.text} />
          <button>{'Add #' + (this.state.items.length + 1)}</button>
        </form>
      </div>
    );
  }
});

React.render(<TodoApp />, mountNode);

A Component Using External Plugins

React is flexible and provides hooks that allow you to interface with other libraries and frameworks. This example uses Showdown, an external Markdown library, to convert the textarea’s value in real-time.

var converter = new Showdown.converter();

var MarkdownEditor = React.createClass({
  getInitialState: function() {
    return {value: 'Type some *markdown* here!'};
  },
  handleChange: function() {
    this.setState({value: this.refs.textarea.getDOMNode().value});
  },
  render: function() {
    return (
      <div className="MarkdownEditor">
        <h3>Input</h3>
        <textarea
          onChange={this.handleChange}
          ref="textarea"
          defaultValue={this.state.value} />
        <h3>Output</h3>
        <div
          className="content"
          dangerouslySetInnerHTML={{
            __html: converter.makeHtml(this.state.value)
          }}
        />
      </div>
    );
  }
});

React.render(<MarkdownEditor />, mountNode);

More info

 http://facebook.github.io/react/docs/tutorial.html

http://facebook.github.io/react/docs/getting-started.html

https://facebook.github.io/react/downloads.html

https://github.com/react-bootstrap/react-bootstrap

Cross Site Request Forgery (CSRF)

[Fuente: http://es.wikipedia.org/wiki/Cross_Site_Request_Forgery]

El CSRF (del inglés Cross-site request forgery o falsificación de petición en sitios cruzados) es un tipo de exploit malicioso de un sitio web en el que comandos no autorizados son transmitidos por un usuario en el cual el sitio web confía. Esta vulnerabilidad es conocida también por otros nombres como XSRF, enlace hostil, ataque de un click, cabalgamiento de sesión, y ataque automático.

Ejemplo

Un ejemplo muy clásico se dá cuando un sitio web, llamemoslo “example1.com”, posee un sistema de administración de usuarios. En dicho sistema, cuando un administrador se loguea, y ejecuta el siguiente REQUEST GET, elimina al usuario de ID: “63”:http://example1.com/usuarios/eliminar/63

Una forma de ejecutar la vulnerabilidad CSRF, se daría si otro sitio web, llamemos “example2.com”, en su sitio web añade el siguiente código HTML: <img src="http://example1.com/usuarios/eliminar/63">

Cuando el usuario administrador (logueado en example1.com), navegue por este sitio atacante, su browser intentará buscar una imagen en la URL y al realizarse el REQUEST GET hacia esa URL eliminará al usuario 63.

404 on jquery min map file

If Chrome DevTools is reporting a 404 for a .map file (maybe jquery-1.10.2.min.mapjquery.min.map or jquery-2.0.3.min.map, but can happen with anything) first thing to know is this is only requested when using the DevTools. Your users will not be hitting this 404.

Now you can fix this or disable the sourcemap functionality.

Fix: get the files

Next, it’s an easy fix. Head to http://jquery.com/download/ and click the Download the map filelink for your version, and you’ll want the uncompressed file downloaded as well.

enter image description here

Having the map file in place allows you do debug your minified jQuery via the original sources, which will save a lot of time and frustration if you don’t like dealing with variable names like a andc.

More about sourcemaps here: An Introduction to JavaScript Source Maps

Dodge: disable sourcemaps

Instead of getting the files, you can alternatively disable JavaScript source maps completely for now, in your settings. This is a fine choice if you never plan on debugging JavaScript on this page. Use the cog icon in the bottom right of the DevTools, to open settings, then: enter image description here

Pusher: adding realtime bi-directional functionality via WebSockets to web and mobile apps

[Fuente: https://pusher.com/docs]

Understanding Pusher

Pusher is a simple hosted API for quickly, easily and securely adding realtime bi-directional functionality via WebSockets to web and mobile apps, or any other Internet connected device.

We offer a rich suite of libraries that you can use within your applications, including a JavaScript client library for web and HTML5 apps.

Our event based abstraction makes it simple to bind UI interactions to events that are triggered from any client or server.

We use WebSockets (with fallbacks to Flash and HTTP in the JavaScript client library) to future proof your applications and make it easy for you to add bi-directional communication to your apps whilst keeping data usage to a minimum.

As well as a WebSockets API, we have a REST API for publishing your messages. This is ideally suited to web server technologies and we have a set of REST API libraries in many common languages to help you to do this.

Pusher with bi-directional WebSockets and REST API
 

We have a simple Publish/Subscribe model based on channels that allows you to filter and control how people receive your messages.

We supply functionality such as authentication mechanisms for private channels, and presence functionality for keeping track of who’s online.

We give you tools for debugging your applications, and if you get stuck, you can always get in touch with us for a chat.

Getting Started

To get started check out the JavaScript quick start guide, the Client API Overview or the Server API Overview. Alternatively have a look at some of the examples of Pusher in use, or checkout some of the resources we have collected.

Getting started with Pusher is very easy. However, if you have any questions get in touch.

This guide uses the JavaScript client API and a selection of Server API libraries. We also have a guide for our iOS client.

Get your free API keys

Create an account, and make a note of your app_idapp_key and app_secret.

Include the Pusher Client library

Open a connection to Pusher

You first need to establish a connection to Pusher. This is done by using your application key (app_key).

var pusher = new Pusher('YOUR_APP_KEY');

Subscribe to a Channel

Now you should subscribe to your first channel.

Note: more info on choosing channel names is available here.

var channel = pusher.subscribe('my-channel');

Listen for events on your channel

Now you can define callbacks that bind to events on a channel, coming in via the connection to Pusher:

channel.bind('my-event', function(data) {
  alert('An event was triggered with message: ' + data.message);
});

Trigger events from your server

In the examples below we trigger an event named my-event to Pusher on a channel called my-channel. For each example below a server library deals with the server communication. If there isn’t an example in a language that you are familiar with then have a look on our server libraries page to see if anyone has created one in your language.

require('Pusher.php');

$pusher = new Pusher($key, $secret, $app_id);
$pusher->trigger('my-channel', 'my-event', array('message' => 'hello world') );

Where next?

Find out about all the cool stuff you can do with channels, Investigate the JavaScript client library or learn how toexcluding event recipients when publishing events.

Channels

Channels are a fundamental concept in Pusher. Each application has a number of channels, and every client can choose which channels it connects to.

Channels provide:

  • A way of filtering data. For example, in a chat application there may be a channel for people who want to discuss ‘dogs’
  • A way of controlling access to different streams of information. For example, a project management application would want to authorise people to get updates about ‘secret-projectX’

We strongly recommend that channels are used to filter your data and that it is not achieved using events. This is because all events published to a channel are sent to all subscribers, regardless of their event binding.

Channels don’t need to be explicitly created, and are instantiated on client demand. This means that creating a channel is easy. Just tell a client to subscribe to it.

Channel Types

There are 3 types of channels at the moment:

  • Public channels can be subscribed to by anyone who knows their name
  • Private channels should have a private- prefix. They introduce a mechanism which lets your server control access to the data you are broadcasting
  • Presence channels should have a presence- prefix and are an extension of private channels. They let you ‘register’ user information on subscription, and let other members of the channel know who’s online

Channel Naming Conventions

Channel names may contain a maximum of 164 characters. This limit includes channel prefixes (i.e. private-and presence- are included in the character count).

Channel names should only include lower and uppercase letters, numbers and the following punctuation_ - = @ , . ;

As an example this is a valid channel name:

foo-bar_1234@=,.;

Accessing channels

If a channel has been subscribed to already it is possible to access channels by name, through the pusher.channelfunction:

var channel = pusher.channel(channelName);
  • channelName (String)
    • The name of the channel to retrieve

Debugging Pusher

We offer a number of really useful features that can help you during development and whilst trying to get to the bottom of problems with your application.

Viewing application events in the Pusher Debug Console

The Pusher Debug Console can be found within the Pusher dashboard and can be used to help you understand what’s happening within your Pusher application.

It will initially indicate if you can connect or not – if you can connect you might briefly see a connection warning dialog. If you can’t connect the connection warning dialog will stay visible.

Once you have connected you can check that connections are being opened and closed, subscriptions are being made, channels are becoming occupied and vacated and that messages are being received by our API for your application. This feature can be really handy during development or when trying to troubleshoot why certain features in your application might not be working.

Sending test events using the Event Creator

The Event Creator is a really handy tool that lets you trigger an event on any channel with any event data directly from your Pusher app dashboard. This feature means you can write your client code to subscribe to a channel and consume an event without the need to write any server code to start off with. Or it can simply be used for checking that your client application is behaving as expected.

Enable logging in the Pusher JavaScript library

To make Pusher a bit more chatty about what is coming in via the socket connection, you can turn on debugging before you initialise your Pusher object. The most common use of this feature is to output all the logging from the Pusher library to the browser console as follows:

Pusher.log = function(message) {
  if (window.console && window.console.log) {
    window.console.log(message);
  }
};

This should create output like the following in your browser (Chrome in this example): 

Automated Diagnostics

We have a Pusher Diagnostics application that runs a number of tests related to the runtime environment (the browser) and the features offered by the Pusher JavaScript library. If you still can’t get to the bottom of a problem running the diagnostics and then getting in touch with support is a good next step.

AngularJS : E2E Testing : Protractor

[Fuente: https://github.com/angular/protractor]

Protractor Build Status

Protractor is an end-to-end test framework for AngularJS applications. Protractor is a Node.js program built on top of WebDriverJS. Protractor runs tests against your application running in a real browser, interacting with it as a user would.

Test Like a User

Protractor is built on top of WebDriverJS, which uses native events and browser-specific drivers to interact with your application as a user would.

For AngularJS Apps

Protractor supports Angular-specific locator strategies, which allows you to test Angular-specific elements without any setup effort on your part.

Automatic Waiting

You no longer need to add waits and sleeps to your test. Protractor can automatically execute the next step in your test the moment the webpage finishes pending tasks, so you don’t have to worry about waiting for your test and webpage to sync.

Protractor vs Angular Scenario Runner

The new, preferred end-to-end testing framework is called Protractor. Unlike the Angular scenario runner, Protractor is built on Selenium’s WebDriver, which is an API, written as extensions, for controlling browsers.

WebDriver has extensions for all sorts of different browsers, including the most popular. We gain speed and stability in our tests by developing against true web browsers.

Luckily, Protractor is built atop the Jasmine framework, so we don’t need to learn a new framework in order to use it. We can also install it as a standalone test runner or embed it in our tests as a library.

Use Protractor in a non-AngularJS app

you only need to access the webdriver instance by using browser.driver:

browser.driver.find(by.css('[data-ptor="submit-btn"]'));		

Getting Started

The Protractor documentation for users is located in the protractor/docs folder.

To get set up and running quickly:

Once you are familiar with the tutorial, you’re ready to move on. To modify your environment, see the Protractor Setup docs. To start writing tests, see the Protractor Tests docs.

To better understand how Protractor works with the Selenium WebDriver and Selenium Sever see the reference materials.

Choosing a Framework

Protractor supports three behavior driven development (BDD) test frameworks: Jasmine, Mocha, and Cucumber. These frameworks are based on JavaScript and Node.js and provide the syntax, scaffolding, and reporting tools you will use to write and manage your tests.

Prerequisites

Protractor is a Node.js program. To run, you will need to have Node.js installed. You will download Protractor package using npm, which comes with Node.js. Check the version of Node.js you have by running node --version. It should be greater than v0.10.0.

By default, Protractor uses the Jasmine test framework for its testing interface. This tutorial assumes some familiarity with Jasmine.

This tutorial will set up a test using a local standalone Selenium Server to control browsers. You will need to have theJava Development Kit (JDK) installed to run the standalone Selenium Server. Check this by running java -version from the command line.

Setup

Use npm to install Protractor globally with:

npm install -g protractor

This will install two command line tools, protractor and webdriver-manager. Try running protractor --version to make sure it’s working.

The webdriver-manager is a helper tool to easily get an instance of a Selenium Server running. Use it to download the necessary binaries with:

webdriver-manager update

Now start up a server with:

webdriver-manager start

This will start up a Selenium Server and will output a bunch of info logs. Your Protractor test will send requests to this server to control a local browser. You can see information about the status of the server at http://localhost:4444/wd/hub.

Write a test

Open a new command line or terminal window and create a clean folder for testing.

Protractor needs two files to run, a spec file and a configuration file.

Let’s start with a simple test that navigates to the todo list example in the AngularJS website and adds a new todo item to the list.

Copy the following into todo-spec.js:

describe('angularjs homepage todo list', function() {
  it('should add a todo', function() {
    browser.get('http://www.angularjs.org');

    element(by.model('todoText')).sendKeys('write a protractor test');
    element(by.css('[value="add"]')).click();

    var todoList = element.all(by.repeater('todo in todos'));
    expect(todoList.count()).toEqual(3);
    expect(todoList.get(2).getText()).toEqual('write a protractor test');
  });
});

The describe and it syntax is from the Jasmine frameworkbrowser is a global created by Protractor, which is used for browser-level commands such as navigation with browser.get.

Configuration

Now create the configuration file. Copy the following into conf.js:

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['todo-spec.js']
};

This configuration tells Protractor where your test files (specs) are, and where to talk to your Selenium Server (seleniumAddress). It will use the defaults for all other configuration. Chrome is the default browser.

Run the test

Now run the test with:

protractor conf.js

You should see a Chrome browser window open up and navigate to the todo list in the AngularJS page, then close itself (this should be very fast!). The test output should be 1 test, 2 assertions, 0 failures. Congratulations, you’ve run your first Protractor test!

Learn More

Learn more with the Tutorial.

The WebDriver Control Flow

The WebDriverJS API is based on promises, which are managed by a control flow and adapted for Jasmine. A short summary about how Protractor interacts with the control flow is presented below.

Promises and the Control Flow

WebDriverJS (and thus, Protractor) APIs are entirely asynchronous. All functions return promises.

WebDriverJS maintains a queue of pending promises, called the control flow, to keep execution organized. For example, consider this test:

  it('should find an element by text input model', function() {
    browser.get('app/index.html#/form');

    var username = element(by.model('username'));
    username.clear();
    username.sendKeys('Jane Doe');

    var name = element(by.binding('username'));

    expect(name.getText()).toEqual('Jane Doe');

    // Point A
  });

At Point A, none of the tasks have executed yet. The browser.get call is at the front of the control flow queue, and thename.getText() call is at the back. The value of name.getText() at point A is an unresolved promise object.

Protractor Adaptations

Protractor adapts Jasmine so that each spec automatically waits until the control flow is empty before exiting. This means you don’t need to worry about calling runs() and waitsFor() blocks.

Jasmine expectations are also adapted to understand promises. That’s why this line works – the code actually adds an expectation task to the control flow, which will run after the other tasks:

  expect(name.getText()).toEqual('Jane Doe');

Migrating Existing Test Scripts (from Angular Scenario Runner)

ptor = protractor instance

browser().navigateTo(url)

ptor.get(url)

browser().location().url()

ptor.getCurrentUrl()

binding(name)

ptor.findElement(protractor.By.binding(‘{{status}}’)).getText()

input(name).enter(value)

ptor.findElement(protractor.By.input(“user”)).sendKeys(value)

input(name).check()

ptor.findElement(protractor.By.input(“user”)).click();

input(name).select(value)

See Select below.

input(name).val()

ptor.findElement(protractor.By.input(“user”)).getText()

repeater(selector, label).count()

ptor.findElements(protractor.By.repeater(“cat in pets”)).length()

repeater(selector, label).row(index)

ptor.findElements(protractor.By.repeater(“cat in pets”)).row(index)

repeater(selector, label).column(binding)

ptor.findElements(protractor.By.repeater(“cat in pets”)).row(index)..column(binding)

select(name).option(value)

ptor.findElement(protractor.By.id(‘selectId’).click();

ptor.findElement(protractor.By.css(‘option [value=”0”]’’).click();

select(name).options(value1, value2…)

ptor.findElement(protractor.By.id(‘selectId’).click();

ptor.findElement(protractor.By.css(‘option [value=”0”]’’).click();

ptor.findElement(protractor.By.css(‘option [value=”2”]’’).click();

ptor.findElement(protractor.By.css(‘option [value=”4”]’’).click();

element(selector, label)

See WebElement Methods Mentioned Earlier

Plugins de Gulp útiles