Grupowanie stanu i logiki w pluginie jComponent
Plugin to kontroler sekcji strony. PLUGIN(name, declaration) go rejestruje, a <ui-plugin path="name"> podłącza do elementu. Wewnątrz sekcji ? w ścieżce oznacza „ścieżkę pluginu”, więc znaczniki nie zależą od tego, gdzie plugin żyje w stanie.
Deklaracja dostaje self (instancję pluginu) i config. self.get() i self.set() działają względem ścieżki pluginu, a self.element to element jQuery <ui-plugin>. Zaimplementuj self.make, aby wykonać kod, gdy plugin jest gotowy. Do zdarzeń DOM użyj self.element: self.on() służy do zdarzeń jComponent, nie do kliknięć.
<!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> Wypróbuj w przeglądarce
Edytuj przykład i uruchom go. Działa w izolowanej ramce w Twojej przeglądarce; nic nie jest wysyłane na nasz serwer.
Podgląd