Seskupení stavu a logiky do pluginu jComponent
Plugin je kontroler jedné sekce stránky. PLUGIN(name, declaration) ho zaregistruje a <ui-plugin path="name"> ho připojí k elementu. Uvnitř sekce znamená ? v cestě „cesta pluginu“, takže značkování nezávisí na tom, kde plugin ve stavu žije.
Deklarace dostane self (instanci pluginu) a config. self.get() a self.set() pracují relativně k cestě pluginu a self.element je jQuery element <ui-plugin>. Implementuj self.make, aby se kód spustil, až je plugin připraven. Pro události DOM použij self.element: self.on() je pro události jComponent, ne pro kliknutí.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jComponent</title>
<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
<ui-plugin path="cart">
<p>Items: <ui-bind path="?.items" config="text:value || 0"></ui-bind></p>
<button type="button" id="add">Add item</button>
</ui-plugin>
<script>
PLUGIN('cart', function(self) {
self.add = function() {
self.set('items', (self.get('items') || 0) + 1);
};
// make() runs when the plugin is ready: initialize the state and the events here
self.make = function() {
self.set('items', 0);
self.element.on('click', '#add', self.add);
};
});
</script>
</body>
</html> Vyzkoušejte to ve svém prohlížeči
Upravte příklad a spusťte ho. Běží v izolovaném rámu ve vašem prohlížeči; na náš server se nic neposílá.
Náhled