browserify-adventure
Version:
learn browserify with this educational adventure
81 lines (57 loc) • 2.64 kB
Plain Text
This time you will create a widget to control a form with a text area.
Your code will be called with something like this:
var Widget = require('widget');
var w = Widget();
w.appendTo(document.body);
w.on('message', function (msg) {
console.log('sending message: ' + msg);
});
Your widget should have a form with a textarea with name="msg" in it.
Here's the HTML you can use:
<form class="send">
<textarea type="text" name="msg"></textarea>
<input type="submit" value="submit">
</form>
Your widget should also use css to set the textarea background color to
"purple" and the foreground color to "yellow". Here is the css you can use
for that:
.send textarea {
background-color: purple;
color: yellow;
}
You can use brfs to load each of these files as strings into your widget
module. To insert the css into the dom, check out the `insert-css` package
from npm.
Like before, you can use the `domify` package from npm to turn the html
string into an html element. Implement an `.appendTo(target)` function that
adds your dom element to the target with `target.appendChild(elem)`.
You can use `elem.querySelector(selector)` to query for references to dom
elements using a css selector string.
Finally, your widget should register a form "submit" listener with
`.addEventListener()` on your html form element. `.addEventListener()` is
part of the dom and you can use it like this:
elem.addEventListener(evname, function (ev) {
ev.preventDefault();
// ...
});
The `ev.preventDefault()` prevents the browser's default handlers from
taking over so that you can implement custom functionality.
Your widget should also have an event-emitter API to emit a `"message"`
event with the textarea content when the user submits the form.
To implement an event-emitter API, you can either return a `new
EventEmitter` from the `events` package that is built into browserify and
node, or you can use the `inherits` package like this:
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
module.exports = Widget;
inherits(Widget, EventEmitter);
function Widget () {
if (!(this instanceof Widget)) return new Widget;
}
then to emit an event, just do `this.emit("evname", args...)`.
Here are the modules you might need for this level:
npm install brfs domify insert-css inherits
If you use brfs, compile your program with:
browserify -t brfs -d -r ./widget.js:widget | $ADVENTURE_COMMAND verify
If you just want to run your solution without verification, do:
browserify -t brfs -d -r ./widget.js:widget | $ADVENTURE_COMMAND run