Skip to content

Instantly share code, notes, and snippets.

@karlwestin
Created May 18, 2013 14:51
Show Gist options
  • Save karlwestin/5604659 to your computer and use it in GitHub Desktop.
Save karlwestin/5604659 to your computer and use it in GitHub Desktop.
Example of using pubsub for communication between Polymer.js widgets. The purpose of this is not to demonstrate pubsub, but to show how to easily blend 'normal' javascript with Polymer components.
<!DOCTYPE html>
<html>
<head>
<title>Polymer</title>
<meta charset="utf-8" />
<script type="text/javascript" charset="utf-8" src="pubsub.js"> </script>
<script type="text/javascript" charset="utf-8" src="polymer/polymer.js"> </script>
<link rel="import" href="publisher.html">
<link rel="import" href="subscriber.html">
</head>
<body>
<publisher></publisher>
<subscriber></subscriber>
</body>
</html>
<element name="publisher">
<template>
<div >Yo i'm the publisher: The value is <strong>{{value}}</strong>.<br>
<h2>that's {{level}}.</h2>
Lower or raise it here:<br>
<input id="valueInput" type="range" value="{{value}}">
</div>
</template>
<script>
Polymer.register(this, {
value: "50",
level: "medium",
valueChanged: function() {
if(this.value > 95) {
this.level = "god damn high"
} else if(this.value > 80) {
this.level = "high"
} else if(this.value > 50) {
this.level = "medium"
} else {
this.level = "low"
}
pubsub.publish("value:changed", this.value);
}
});
</script>
</element>
/*
just a shim for some pubsub thing. Ignore and use something else :)
*/
window.pubsub = (function() {
var callbacks = [];
function publish() {
var event = arguments[0],
args = [].slice.call(arguments, 1),
re = new RegExp("^" + event + "$");
console.log(event);
callbacks.forEach(function(call) {
if(re.test(call.key)) {
call.handler.apply(call.context, args);
} else {
console.log("didn't");
}
});
}
function subscribe(key, handler, context) {
context = context || {};
callbacks.push({
key: key,
handler: handler,
context: context
});
}
return {
publish: publish,
subscribe: subscribe
};
})();
<element name="subscriber">
<template>
<h5>The subscriber: {{value}}</h5>
</template>
<script>
Polymer.register(this, {
ready: function() {
pubsub.subscribe("value:changed", function(val) {
this.value = val;
}, this);
},
value: "unset"
});
</script>
</element>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment