Return generated Typekit id in Yeoman Generator - javascript

I'm using node-typekit to create a new Typekit empty font set in my Yeoman generator for use in my project. I am able to successfully create the kit, but cannot figure out how to return the kit id value back to the Yeoman generator so I can add the necessary Typekit script tag values to my web pages. Here is the part of my index.js generator script in question:
At the top of index.js:
var kit = require('typekit');
var typekitID = '';
function setTypekitID(theid) {
typekitID = theid;
};
And the app section:
app: function () {
var token = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var split = this.domainname.split('.');
split.pop();
var localdomain = split.join('.') + '.dev';
kit.create(token, {
name: this.appname,
badge: false,
domains: [this.domainname, localdomain],
families: []
}, function (err, data) {
setTypekitID(data.kit.id);
});
}
If instead of:
setTypekitID(data.kit.id);
I use:
console.log(data.kit.id);
The correct kit ID is displayed in the console. However, I can't quite figure out how to pass the data.kit.id value in the callback back to the generator for further use. Given the current code above, it comes back as "undefined".
Any ideas? Thanks!

Without any experience with typekit, I would guess that kit.create is an asynchronous call. When you make such a call, the generator needs to know about it, so it can delay invocation of further methods until it knows your asynchronous callback has had a chance to execute.
Try doing this:
app: function () {
var done = this.async(); // this tells the generator, "hang on, yo."
// ...
kit.create(token, { /* ... */ }, function (err, data) {
setTypekitID(data.kit.id);
done(); // calling this resumes the generator.
});
}
An example of how the default generator-generator uses this can be found here.

Related

Update HTML object with node.js and javascript

I'm new to nodejs and jquery, and I'm trying to update one single html object using a script.
I am using a Raspberry pi 2 and a ultrasonic sensor, to measure distance. I want to measure continuous, and update the html document at the same time with the real time values.
When I try to run my code it behaves like a server and not a client. Everything that i console.log() prints in the cmd and not in the browesers' console. When I run my code now i do it with "sudo node surveyor.js", but nothing happens in the html-document. I have linked it properly to the script. I have also tried document.getElementsByTagName("h6").innerHTML = distance.toFixed(2), but the error is "document is not defiend".
Is there any easy way to fix this?
My code this far is:
var statistics = require('math-statistics');
var usonic = require('r-pi-usonic');
var fs = require("fs");
var path = require("path");
var jsdom = require("jsdom");
var htmlSource = fs.readFileSync("../index.html", "utf8");
var init = function(config) {
usonic.init(function (error) {
if (error) {
console.log('error');
} else {
var sensor = usonic.createSensor(config.echoPin, config.triggerPin, config.timeout);
//console.log(config);
var distances;
(function measure() {
if (!distances || distances.length === config.rate) {
if (distances) {
print(distances);
}
distances = [];
}
setTimeout(function() {
distances.push(sensor());
measure();
}, config.delay);
}());
}
});
};
var print = function(distances) {
var distance = statistics.median(distances);
process.stdout.clearLine();
process.stdout.cursorTo(0);
if (distance < 0) {
process.stdout.write('Error: Measurement timeout.\n');
} else {
process.stdout.write('Distance: ' + distance.toFixed(2) + ' cm');
call_jsdom(htmlSource, function (window) {
var $ = window.$;
$("h6").replaceWith(distance.toFixed(2));
console.log(documentToSource(window.document));
});
}
};
function documentToSource(doc) {
// The non-standard window.document.outerHTML also exists,
// but currently does not preserve source code structure as well
// The following two operations are non-standard
return doc.doctype.toString()+doc.innerHTML;
}
function call_jsdom(source, callback) {
jsdom.env(
source,
[ 'jquery-1.7.1.min.js' ],
function(errors, window) {
process.nextTick(
function () {
if (errors) {
throw new Error("There were errors: "+errors);
}
callback(window);
}
);
}
);
}
init({
echoPin: 15, //Echo pin
triggerPin: 14, //Trigger pin
timeout: 1000, //Measurement timeout in µs
delay: 60, //Measurement delay in ms
rate: 5 //Measurements per sample
});
Node.js is a server-side implementation of JavaScript. It's ok to do all the sensors operations and calculations on server-side, but you need some mechanism to provide the results to your clients. If they are going to use your application by using a web browser, you must run a HTTP server, like Express.js, and create a route (something like http://localhost/surveyor or just http://localhost/) that calls a method you have implemented on server-side and do something with the result. One possible way to return this resulting data to the clients is by rendering an HTML page that shows them. For that you should use a Template Engine.
Any DOM manipulation should be done on client-side (you could, for example, include a <script> tag inside your template HTML just to try and understand how it works, but it is not recommended to do this in production environments).
Try searching google for Node.js examples and tutorials and you will get it :)

Access parameter of Node.js module function

im totally new to node.js and i couldn't find a similar question for my problem. I'm sure it's easy to solve for one of u guys... at least i guess.
I'm trying to get a special paragraph of a wikipage using the npm mediawiki module for node.js! I get the paragraph using the pre-defined function as following:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
});
Thats working. What i want is: to use "result" outside of that code block in other functions. I think it has something to do with callbacks but im not sure how to handle it as this is a pre-defined function from the mediawiki module.
The example function of the module to get a wikipage looks as following:
/**
* Request the content of page by title
* #param title the title of the page
* #param isPriority (optional) should the request be added to the top of the request queue (defualt: false)
*/
Bot.prototype.page = function (title, isPriority) {
return _page.call(this, { titles: title }, isPriority);
};
which uses the following function of the module:
function _page(query, isPriority) {
var promise = new Promise();
query.action = "query";
query.prop = "revisions";
query.rvprop = "timestamp|content";
this.get(query, isPriority).complete(function (data) {
var pages = Object.getOwnPropertyNames(data.query.pages);
var _this = this;
pages.forEach(function (id) {
var page = data.query.pages[id];
promise._onComplete.call(_this, page.title, page.revisions[0]["*"], new Date(page.revisions[0].timestamp));
});
}).error(function (err) {
promise._onError.call(this, err);
});
return promise;
}
There's also a complete callback function and i dont know how to use it:
/**
* Sets the complete callback
* #param callback a Function to call on complete
*/
Promise.prototype.complete = function(callback){
this._onComplete = callback;
return this;
};
How can i access the "result" variable by using callbacks outside the function of the module? I don't know how to handle the callback as it is a pre-defined function of a module...
What i want is: to use "result" outside of that code block in other functions.
You can't. You need to use the result inside that code block (that code block is called a callback function btw.). You can still pass them to other functions, you just need to do it inside that callback function:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
other_function(result); // <------------- this is how you use it
});

How to setup yeoman test for subgenerator that reads package.json

I have a subgenerator that uses the name from the package.json. Now I want to test that function and wrote a before() that is supposed to create a dummy package.json for the test.
Problem is that the subgenerator cannot read the dummy json file.
test file:
before(function (done) {
helpers.run(path.join( __dirname, '../addcomponent'))
.inDir(path.join( __dirname, './tmp'), function(dir) {
fs.copyTpl(
path.join(__dirname, '../app/templates/_package.json'),
dir + 'package.json',
{ ProjectName: 'foo' }
);
var test = fs.readJSON(dir + 'package.json');
console.log('test: ' + test); // returns the object
console.log('test.name: ' + test.name); // returns the correct name
})
.withArguments(['foo'])
.withPrompts(prompts)
.withOptions(options)
.on('end', done);
});
but in my sub-generator:
var memFs = require('mem-fs');
var editor = require('mem-fs-editor');
var store = memFs.create();
var fs = editor.create(store);
...
init: function() {
this.pkg = this.fs.readJSON('package.json');
console.log('this.pkg: ' + this.pkg); // returns undefined
}
// or
init: function() {
this.on('ready', function() {
this.pkg = this.fs.readJSON('package.json');
console.log('this.pkg: ' + this.pkg); // returns undefined
});
}
// or
anyOther: function() {
this.pkg = this.fs.readJSON('package.json');
console.log('this.pkg: ' + this.pkg); // returns undefined
}
The whole setup can be found here: https://travis-ci.org/markusfalk/generator-kickstart/builds/58892092
thanks for any help
Edit: I'll keep the old answer underneath and that's probably relevant to most people running into this issue, but not to you.
The idea behind mem-fs is to have an in memory store. It doesn't write anything to disk automatically. As so, it keep the state in the mem-fs instance. In this case, you're creating your own mem-fs instance, while yeoman use another instance. This mean the file you write is never seen by Yeoman (and never written to disk).
For you, the fix would be to use the generator instance provided as the first parameter of the ready event.
helpers.run(path.join( __dirname, '../addcomponent'))
.on('ready', function (generator) {
generator.fs.write('file.txt', 'foo');
});
Another option is to use the node.js sync fs methods. (fs.writeFileSync(), etc)
My guess is you're using this.fs.readJSON() inside your generator constructor.
The constructor is initialized before the ready event is triggered. This mean you read the file before it is actually written.
The usual fix is to never read inside the constructor. You can delay this step until the initializing phase where the inDir() (or the ready event) callback has run.
As a side note, you should use inTmpDir() rather than inDir()

Problems when testing (whilst using javascript & QUnit)

Given the following code, I have managed to write a test by making use of QUnit for the first part but was unable to test finder.doRoutefinding. How can I 'mock'the function finder.doRoutefinding? (Mockjax cannot be used here since no ajax calls are involved)
`finder.doSelectDestination = function(address)
{
finder.destination = address;
finder.doRoutefinding(
finder.departure,
finder.destination,
finder.whenRouteLoaded,
finder.showRoute);
}
test('Destination Selector',
function()
{
address="London";
finder.doSelectDestination(address);
equal(pathfinder.destination,address, "Succesful Destination Selection");
}
);
There are caveats, but you could simply replace the function with your mock:
var originalDoRoutefinding = finder.doRoutefinding;
finder.doRoutefinding = function() {
// Mock code here.
};
// Test code here.
finder.doRoutefinding = originalDoRoutefinding;
If that kind of thing works for you, you might consider using a library like Sinon.JS.

WinJS: Loading data

I'm trying to develop my first Windows 8 Store app (HTML/JS). I am using the Grid App Template which suites my Needs I think the best.
This is my model:
I have three entities: 1. GalleryCategory 2. Gallery 3. GalleryItem.
A Gallery is linked to exactly one Category. A GalleryItem is linked to exactly one Gallery...so nothing fancy here...
I'm using the out of the box data.js file to load all categories and all galleries on the Startup of the app. But when I open the galleryDetail.html (which is supposed to Show all the Images of the particular Gallery) I want to load all Images of the Gallery then. (to avoid to much loading on the beginning).
And now I'm finally coming to the Point that I do not understand:
How can I manage this?? I mean
WinJS.UI.Pages.define("/pages/galleryDetail/galleryDetail.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0);
element.querySelector(".titlearea .pagetitle").textContent = item.group.title;
element.querySelector("article .item-title").textContent = item.title;
element.querySelector("article .item-subtitle").textContent = item.subtitle;
element.querySelector("article .item-image").src = item.backgroundImage;
element.querySelector("article .item-image").alt = item.subtitle;
element.querySelector("article .item-content").innerHTML = item.content;
element.querySelector(".content").focus();
var galleryId = item.key;
WinJS.xhr({ url: "http://someUrlToAnAspNetWebsite/Handlers/GalleryItemsHandler.ashx?galleryId=" + galleryId }).done(
// Complete function
function (response) {
var items = JSON.parse(response.responseText);
items.forEach(function (item) {
galleryItemsList.push(item);
});
dataList = new WinJS.Binding.List(galleryItemsList);
var galleryItemsListView = document.getElementById('galleryItemsListView').winControl;
galleryItemsList.itemDataSource = dataList.dataSource;
},
// Error function
function (response) {
// handle error here...
},
// Progress function
function (response) {
// progress implementation goes here...
}
);
},
my Problem is obivous...the ready function continues / Ends before the data is retrieved...as the async call takes a while.
But I thought using the promise (.done()) will do this for me (synchronising the threads)?? Or do I need to use the join() function. If so, where and how?? Sorry for my issues with this...
Thanks for any help...
The ready function itself is an async function, so you only have to return a promise to tell its caller that its not done until some promise is resolved. So you can fix your issue with 7 key strokes. Just add return before the WinJS.xhr call.

Categories

Resources