Back Home

React and Flux

Flux is an architecture that Facebook uses internally when working with React. It is not a framework or a library. It is simply a new kind of architecture that complements React and the concept of Unidirectional Data Flow.

That said, Facebook does provide a repo that includes a Dispatcher library. The dispatcher is a sort of global pub/sub handler that broadcasts payloads to registered callbacks.

A typical Flux architecture will leverage this Dispatcher library, along with NodeJS's EventEmitter module in order to set up an event system that helps manage an applications state.

Flux is probably better explained by explaining its individual components:

  • Actions - Helper methods that facilitate passing data to the Dispatcher
  • Dispatcher - Receives actions and broadcasts payloads to registered callbacks
  • Stores - Containers for application state & logic that have callbacks registered to the dispatcher
  • Controller Views - React Components that grab the state from Stores and pass it down via props to child components.

HelloWorld React

there is a starter command

npm install -g create-react-app
create-react-app my-app

cd my-app
npm start

The basic javascript app framework is nice and simple

if (Meteor.isClient) {
 
// add browser client code here 
} 
 
if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

the code interacts with the Meteor handlebar like template language callued Spacebars it has been tailored to produce reactive Meteor templates when compiled.

Forms Builder

Meteor Template Basics

The html part is defined using a template tag

<template name="leaderboard">
  Hello World
</template>

and the template is displayed anywhere in the html document with

{{> leaderboard}}

For each templates we can have associated functions

Template.leaderboard.helpers({
'player': function(){ 
    return "Some other text"
},
'otherHelperFunction': function(){
  return "Some other function"
}});

these functions can be referenced in the template with {{player}} and {{otherHelperFunction}}

Bringing the data and template together we can use the {{each}} function to print collection data In the helper function

return playerCollection.find();

and the template

{{# each player}}
   {{name}}
{{/ each}}

Events

Similar to displaying template data ..events can be configured in templates

Template.leaderboard.events({
'click': function(){
 // code goes here
}});

this is the most generic and clicking anywhere inside the template area triggers the event. To narrow the selection you can use jquery like selection on any html fields, div's etc

<li class="player">
{{name}}: {{score}}
</li>

each item on the list cab be trigged by

'click .player': function (){
    console.log("You clicked a .player element");  // your event action
}

Meteor - Interacting with Data

By default Meteor comes with Mongo bindings (see other data options below). To create a simple collection in mongo that is data bound to the Meteor template:

 MyCollection = new Mongo.Collection("my-collection"); 
  • On the server, this sets up a MongoDB collection called my-collection
  • on the client, this creates a cache connected to the server collection.

Note: the word “var” is not placed before the variable to make it global so we can use it throughout all of our files

Enter the variable in the chrome Javascript inspector and it should show the variable is a mongo collection We can even enter data through the console

MyCollection.insert({name: "David", score: 0});

the full Meteor Colleciton api. With the highlights being:

  • collection.find - Find the documents in a collection that match the selector.
  • collection.findOne - Finds the first document that matches the selector, as ordered by sort and skip options.
  • collection.insert - Insert a document in the collection. Returns its unique _id.
  • collection.update - Modify one or more documents in the collection. Returns the number of affected documents.
  • collection.upsert - Modify one or more documents in the collection, or insert one if no matching documents were found. Returns an object with keys numberAffected (the number of documents modified) and insertedId (the unique _id of the document that was inserted, if any).
  • collection.remove - Remove documents from the collection
  • collection.allow - Allow users to write directly to this collection from client code, subject to limitations you define.
  • collection.deny - Override allow rules.

Data Dependencies

Meteor works by sending the html first, then the data later. When your rendered callback fires, the data may not or may have been sent.

Pub/Sub

  • Forcing Template re-draw on data. The most natural way to force a redraw when data is changed is to use a dependency on that data.
var friends = [];
var friends_dep = new Deps.Dependency();

Template.myTemplate.friends_list = function() {
    friends_dep.depend();    /* Causes the helper to rerun when data changes */
    return friends;
};

...

function callback() {
    ...
    friends = response.data;
    friends_dep.changed();    /* Call this after you set the new data */
}

Meteor and Jquery

Meteor doesn't use $(document).ready, instead you should use Meteor.startup which is equivalent :

Meteor.startup(function() {
    if ( $('section#main').hasClass('postlist')) {
        Session.set('pageTitle', 'Posts list');
    };
});

Note: * Client loads javascript from: project/public and project/client

  • Server loads javascript from: project/public and project/server folders.

As of v1.0, Meteor is using jQuery internally in the client, so you can use your library directly without adding jQuery. However, it's recommended that you add jQuery to your Meteor project explicitly:

meteor add jquery

The Meteor docs explain in depth how JavaScript files are loaded and where static assets should go (CSS, images). but basically if added the packages are available without having to explicitly load

See also how to repackage an existing library for Meteor

Routing

It seems to be recommend to use IronRouter a router that works on the server and the browser, designed specifically for Meteor. Install in the usual way

> meteor add iron:router

To update iron:router to the latest version you can use the meteor update command:

> meteor update iron:router

Basic routing:

Create some routes in a client/server JavaScript file:
 
Router.route('/', function () {
  this.render('MyTemplate');
});
 
Router.route('/items', function () {
  this.render('Items');
});
 
Router.route('/items/:_id', function () {
  var item = Items.findOne({_id: this.params._id});
  this.render('ShowItem', {data: item});
});

Rest Interfaces

Meteor. They have a http package of their own, you won't need the custom XHR that lives in our SDK.

Meteor.http.get(url, [options], [asyncCallback])

that can also be used with Iron Router

Deploying Meteor

Build and deploy to nodejs or look at

  • Meteor-up - puppet/chef like automatic deploy to linux servers

Testing Meteor

  • Velocity the official Meteor test framework == Debugging Node and Meteor ==

To debug meteor app in IDE on server side, you can do following:

  1. Install NodeJS plugin from the Plugin Repository.
  2. Configure $NODE_OPTIONS environment variable to have “–debug=47977” value.

To accomplish that you can change directory to your meteor app and launch meteor like this: $ NODE_OPTIONS=“–debug=47977” meteor 3) Create a Node.js Remote Debug run configuration and fill in the fields: Host : 127.0.0.1 (host of meteor app running, leave untouched if meteor is running on your local machine) Debug port : 47977 (or any other port, it should just stay in sync with $NODE_OPTIONS environment variable configured on step 2)

Local directory : /path/to/your/meteor/project/.meteor/local/build/app
Remote path : app

https://youtrack.jetbrains.com/issue/WEB-6264

Social Apps

Misc

* Meteor Blogs MeteorHacks blog BulletProofMeteor

* Meteor Api packages Meteor Linkedin Meteor Jquery Datatable Meteor flot with live example meteor inline edit demo meteor facebook api oauth yelp connection yahoo finance hopscotch product intro tour

  • Oauth
    • oauth.io simplifed oauth? for a price 500 api calls for free and $19 afterwards

* Storage Options mongo is out of the box Meteor Redis

* Consider meteori-izing raml4js as part of the node raml packages

Other Frameworks

 
nodejs_notes.txt · Last modified: 2017/08/21 00:55 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd