Structuring a multi-view (multiple pages) Knockout.js app - javascript

I've been working with Knockout.js for a couple of weeks now doing examples and other tutorials, but I'm still trying to figure out how to structure everything on the app I'm working on. It's a simple school backend app that keeps a list of all the classes, grades, teachers, attendance, and students. It has multiple pages:
list of all the clases (where you can add/edit/remove classes)
each class has a list its students (where you can add/edit/remove students)
each student has a list of his/her attendance and grades
teachers page
school subjects page
and others ...
How do I go about structuring this app? I've already started on the 'classes' page by creating a Class Model:
function Class(data) {
var self = this;
self.id = data.id;
self.name = ko.observable(data.name);
self.students = data.students;
self.attendance = data.attendance;
}
... and a Class ViewModel that loads the initial content (list of classes). It also contains a function to add, edit and remove classes.
function ClassViewModel() {
var self = this;
self.classes = ko.observableArray(ko.utils.arrayMap(classArr, function(eachClass) {
return new Class(eachClass);
}));
[...]
}
So do I continue doing a separate Model and ViewModel for each major part of the app (students, teachers, subjects, etc) and bind them separately on their own pages? And if I go this route, how do I go about sharing functions between ViewModels without having the same function added to each of them?

I have created a convention over configuration library for KO called Knockout.BindingConventions.
https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki
Install using nuget
Install-Package Knockout.BindingConventions
One feature of that library is its template convention, basically it understands that a viewmodel named ClassViewModel should be connected to a template (View) called ClassView
http://jsfiddle.net/xJL7u/
I've also created a template bootstrapper that utilizes above library
https://github.com/AndersMalmgren/Knockout.Bootstrap/wiki
Install using nuget
Install-Package Knockout.Bootstrap
With these two libraries combined you can structure your application like this on server (Using your ClassViewModel as example)
app
Class
ClassViewModel.js
OtherViewModel.js
Shared
DatePickerViewModel.js
views
Class
ClassView.htm
OtherView.htm
Shared
DatePickerView.htm
Fully working MVC4 demo here
https://github.com/AndersMalmgren/Knockout.Bootstrap.Demo

Related

EventDriven NodeJS App Architecture with Lifecycle Hooks

I have a general question about developing a Nodejs App with own lifecycles and events to track serveral activities globally.
What do I need?
Any
References
Tips and Tricks
Blueprints
Frameworks
Background
In have developed a backend with database, authentification and fileupload. I made that very pragmatic and it works fine. But now I want to develop a new better architecture, which is event driven to track activities and lifecycle hooks to init modules.
I was researching about Libs, which seems to be great, but I need to know, if I am on a right way.
Here is the recent backend, which I want to renew from core:
#fractools/node
Goal
The Node needs to be more abstract and event driven to track activities more globally for the hole process.
I was thinking about a core module, which defines the basement for events and hooks which listen to the hole application process.
So other modules like database handling, or authentification etc can be wrapped onto it.
My questions
How can I have a helper like a activity logger, which is listening through the hole app, so I dont need to import a logger in every single action? Is it possible? Does this make any sense?
Example Case
Core module tracks database acivities:
System puts Data into Database, core listen to it, tracks it and pushs this information into a Logger, which uses a Database.
Issue
I stuck for example at one simple architecture thing:
If I have a Database Class, and I want the Core, which is an extended EventErmitter, listen to database actions, I cant have a logger inside Core, which uses database, because i cant reference those modules to eachother at once:
// Core Module
const EventErmitter = require('events');
const Database = require('./database)';
module.exports = class Core extends EventEmitter {
constructor() {
super();
this.logger = new Database('Logger');
this.on('mounted', () => {
this.logger.put('instance mounted')
});
this.on('putData', () => {
this.logger.put('dataPut')
});
this.emit('mounted');
}
}
// Database Module
const Core = require('./core');
const PouchDB = require('pouchdb'); // Which database lib to use is not important yet
let core = new Core();
module.exports = class Database {
constructor(name, options) {
this.id = generateID();
this.name = name;
this.created = JSON.stringify(new Date()); // TODO doubled Quotes
this.options = options || {};
this.db = new PouchDB(name);
core.emits('mounted')
}
put(data) {
this.db.put(data);
core.emits('dataPut')
}
}
So I noticed, I need any starting point. :s
I have had a look into NodeJS EventErmitter and found out that the NodeJS Process is also laying on EventErmitter.
I also have had a look into several Tuts for NodeJS Lifecycle Events, but it does not really to help to start the architecture anyway.
I hope, some of you have good references or 'blueprints', which helps me to develope a good core for my node. :)
Have a nice day so far and stay safe!
Greetings

Vue.js : Best way to implement MPA(Multi page app) in laravel

I have been looking around for quite a time, But didn't got anything convening.
What will be the best approach and practice to implement Vue MPA architecture in laravel.
Searched for quite a bit. But there isn't anything which will give you a clear idea. Your answer will help alot, Please make it brief.
It will also be helpful to answer the point :
Is it a good idea to use just laravel as a data API, And keep Vue
separate from laravel ?
Best approach for implementing hybrid of SPA and MPA.
Some options that I've already used:
Use Laravel to render the "main view" + connect vue.js application.
Basically laravel will render the Vue application and every request goes throught an API.
Easy to setup
Authentication + user validation is easier (you can use laravel session manager for that - don't need to build/use tokens or whatever. "No need to worry about your application state".)
Easy to "disconnect" from Laravel - if you choose in the future to decouple the SPA application.
Use laravel (or lumen) only as an API, and on another server render a SPA.
This can take more time, since you'll need to setup an extra server, prepare cross-origin, etc.
Also easy to setup, but can take more time than option #1
You'll need to create something for user validation/state management, etc.
Easy to place into laravel, if you decide in the future to use "only one app".
Can be easier to maintain/scale (if you have a frontend team, they don't need to worry about laravel - same for your "laravel team", they "won't need to worry" about the frontend)
Laravel + Vue = "one application"
You can use Laravel to render all views + vuejs for components/elements in the page.
Easy to setup. You have laravel + vuejs, and they are already prepared to be used together. https://laravel.com/docs/5.5/frontend#writing-vue-components
Not so easy to decouple. In this case you'll need to create the same views for vue.js. This can take time.
This is the "traditional web development" (in my opinion). If I had to start a project like this today, I wouldn't create all pages in Vue.js + something in Laravel (Controller + new route) to render this view. If you do this (again - my opinion), it's just extra work. If you are worried about SEO, there are "fallbacks"/extra options.
--
All options are testable + scalable.
It also depends on how you start (Should I worry about how I'll decouple the app in the future? Laravel + Vue will be for good?), how your team will work (Does the frontend team really needs to setup laravel or they only need to worry about the frontend code?), etc.
Not sure if i answered your question, if not, please leave a comment.
You haven't found anything clear because there isn't really anything to talk about other than 'What feels right to your understanding and project needs'. If you found yourself very unsure, feel free to dive into doing whatever makes sense to you and then re-adjust the structure when you gain more experience.
Also, read books about system architecture, those will help a lot.
Is it a good idea to use just laravel as a data API, And keep Vue separate from Laravel?
By this, I'm assuming you mean a SPA? Honestly, if your application is small, then I see this is fine.
Larger applications tend to be difficult to maintain if they were SPA.
Read: https://medium.com/#NeotericEU/single-page-application-vs-multiple-page-application-2591588efe58
If you end up using Laravel as an API endpoint, then use the stripped down version of it, Lumen, because it comes without Blade and few other stuff. Lumen is stripped down version to act as an API-endpoint.
Best approach for implementing hybrid of SPA and MPA.
From my experience having attempted to build 4+ projects as hybrids, here's what I found the most optimal structure:
My example will be about an app that saves 'Posts'.
1. Use a repository design pattern.
This one will save you a lot of headache in maintaining your code and maintain a DRY (Don't Repeat Yourself) concept on your code.
Create a directory App\Repositories\
Make a new class PostsRepository. This one will be the one communicating with the database and contains most of the logic.
Create the directory App\Services\
Make a new class PostsService. This one will have the PostsRepository in its constructor.
The service class will be one handling taking user's input whether from the Web controller or the API controller.
<?php
namespace App\Service;
use App\Repositories\PostsRepository;
class PostsService;
{
protected $repository;
public function __construct(PostsRepository $repository)
{
$this->repository = $repository;
}
}
Make a seperation between Web and API controllers.
For web controllers, you create the controller like usual:
php artisan make:controller PostsController
For API controllers, you create the controller to be inside an Api folder.
php artisan make:controller Api\PostsController
The last command will create the directory App\Http\Controllers\Api and have the controller be placed in it.
Recapping
Now we have different controllers to return results appropriate to the startpoint (web / api).
We have services that both the (web / api) controllers send their data to be validated (and have the action taken by the repository).
Examples:
<?php
namespace App\Http\Controllers;
use App\Service\PostsService;
class PostsController extends Controller
{
protected $service;
public function __construct(PostsService $service)
{
$this->service = $service;
}
public function index()
{
/**
* Instead of returning a Blade view and
* sending the data to it like:
*
* $posts = $this->service->all();
* return views('posts.index', compact('posts'));
*
* We go ahead and just return the boilerplate of
* our posts page (Blade).
*/
return view('posts.index');
}
}
...
<?php
namespace App\Http\Controllers\Api;
use App\Service\PostsService;
class PostsController extends Controller
{
protected $service;
public function __construct(PostsService $service)
{
$this->service = $service;
}
/**
* Returns all posts.
*
* A vue component calls this action via a route.
*/
public function index()
{
$posts = $this->service->all();
return $posts;
}
/**
* Notice we don't have a store() in our
* Web controller.
*/
public function store()
{
return $this->service->store();
}
}
...
<?php
namespace App\Services;
use App\Repositories\PostsRepository;
class PostsService extends Controller
{
protected $repository;
public function __construct(PostsRepository $repository)
{
$this->repository = $repository;
}
public function all()
{
$posts = $this->repository->all();
return $posts;
}
public function store()
{
$request = request()->except('_token');
$this->validation($request)->validate();
return $this->repository->store($request);
}
public function validation(array $data)
{
return Validator::make($data, [
'content' => 'required|string|max:255',
//
]);
}
}
In our PostsRepository we actually call methods that save the data. E.g. Post::insert($request);.
2. Dedicate an API group
Route::prefix('api/v1')->middleware('auth')->group(function() {
Route::post('posts/store', 'Api\PostsController#store')->name('api.posts.store');
});
Giving API routes a ->name() helps when you make phpunit tests.
3. Blade views
Those are ought to be stripped-down simple.
views/posts/index.blade.php:
#extends('layouts.app', ['title' => trans('words.posts')])
#section('content')
<!-- Your usual grid columns and stuff -->
<div class="columns">
<div class="column is-6">
<!-- This comp. can have a modal included. -->
<new-post-button></new-post-button>
<div class="column is-6">
<posts-index-page></posts-index-page>
</div>
</div>
#endsection
4. Vue structure.
https://github.com/pablohpsilva/vuejs-component-style-guide
So those Vue components might live in resources/assets/js/components/posts/ where inside /posts/ I'd have folders titled for example IndexPage, CreateModal, EditModal with each folder having its .vue and README.md.
I'd use the <posts-index-page> in index.blade.php and drop in the <post-create-modal> and <edit-post-modal> whenever I want.
All the vue components will use the API endpoint we specified in our Routes file.

Backbone.js: Routing for nested views

I'm trying to figure out following scenario:
Lets say that I have two views: one for viewing items and one for buying them. The catch is that buying view is a sub view for viewing.
For routing I have:
var MyRouter = Backbone.Router.extend({
routes: {
'item/:id': 'viewRoute',
'item/:id/buy': 'buyRoute'
}
});
var router = new MyRouter;
router.on("route:viewRoute", function() {
// initialize main view
App.mainview = new ViewItemView();
});
router.on("route:buyRoute", function() {
// initialize sub view
App.subview = new BuyItemView();
});
Now if user refreshes the page and buyRoute gets triggered but now there is no main view. What would be best solution to handle this?
I am supposed that the problem you are having right now is that you don't want to show some of the stuff inside ViewItem inside BuyView? If so then you should modularized what BuyView and ViewItem have in common into another View then initialize it on both of those routes.
Here is a code example from one of my apps
https://github.com/QuynhNguyen/Team-Collaboration/blob/master/app/scripts/routes/app-router.coffee
As you can see, I modularized out the sidebar since it can be shared among many views. I did that so that it can be reused and won't cause any conflicts.
You could just check for the existence of the main view and create/open it if it doesn't already exist.
I usually create (but don't open) the major views of my app on booting up the app, and then some kind of view manager for opening/closing. For small projects, I just attach my views to a views property of my app object, so that they are all in one place, accessible as views.mainView, views.anotherView, etc.
I also extend Backbone.View with two methods: open and close that not only appends/removes a view to/from the DOM but also sets an isOpen flag on the view.
With this, you can check to see if a needed view is already open, then open it if not, like so:
if (!app.views.mainView.isOpen) {
//
}
An optional addition would be to create a method on your app called clearViews that clears any open views, perhaps with the exception of names of views passed in as a parameter to clearViews. So if you have a navbar view that you don't want to clear out on some routes, you can just call app.clearViews('topNav') and all views except views.topNav will get closed.
check out this gist for the code for all of this: https://gist.github.com/4597606

Backbone.js singular Models not in collection

Being new to Backbone.js, just wanted to clarify the correct way to go about this simple task.
Developing a web app, almost always, you'll have user accounts, where users can login to your app, and view their personalized data. Generally, their page might show some widgets, their user information (name, avatar, etc).
Now creating a Model per widget and grouping these in a Collection is an easy concept. However, would their user info be stored in a singular Model, which would not be apart of a Collection?
If so, how is the hooked up with the rest of the app? Forgive my ignorance, but I've yet to come across any examples that don't explain Models not using them in Collections (User and Users, Dog, Cat and Animals, etc)
Anyway, sorry for the lengthly explanation. I would be looking for any resources to get me started on making a real-world app, rather than a ToDo app (which is great for the basic concept understanding)
There is not any reason to feel forced to declare a Collection for every Model your App has. It is very common to have Models without Collection associated.
// code simplified and not tested
App.CurrentUser = Backbone.Model.extend({
url: "http://myapp.com/session.json"
});
App.CurrentUserView = Backbone.View.extend({
el: "#user-info",
render: function(){
this.$el.html( "<h1>" + this.model.get( "name" ) + "</h1>" );
}
});
var currentUser = new App.CurrentUser();
currentUser.fetch();
var currentUserView = new App.CurrentUserView()({ model: currentUser });
currentUserView.render();
If you want a model / view with no collection, don't write a collection or collection view.
Add the view the same way you normally see the collection based view added.

How to structure a single page app with knockout.js?

I am mostly wondering how to organize things like modal windows, and dynamic pages like profiles. Should the viewModel only contain one profile view or contain all profiles loaded? This here just doesnt seem very "clean".
viewModel = {
profile: ko.observableArray([
new ProfileViewModel()
//... any others loaded
])
, createPostModal: {
input: ko.observable()
, submit: //do something to submit...
}
}
<div data-bind="foreach: profile"><!-- profile html --></div>
<div data-bind="with: createPostModal"></div>
This way doesn't seem very consistent. Is there anybody who has built a single page app with knockout that can offer some advice? Code samples would be appreciated.
We are just starting down this path at work, and so are not quite sure what we're doing. But here's the idea we have.
The page should be composed of any number of "components," possibly nested. Each component has a view model and one public method, renderTo(el), which essentially does
ko.applyBindings(viewModelForThisComponent, el)
It also could have the ability to render subcomponents.
Constructing or updating a component consists of giving it a model (e.g. JSON data from the server), from which it will derive the appropriate view model.
The app is then created by nesting a bunch of components, starting with a top-level application component.
Here is an example for a "hypothetical" book-managing application. The components are LibraryUI (displays a list of all book titles) and DetailsUI (a section of the app that displays details on a book).
function libraryBookViewModel(book) {
return {
title: ko.observable(book.title),
showDetails: function () {
var detailsUI = new BookDetailsUI(book);
detailsUI.renderTo(document.getElementById("book-details"));
}
};
}
function detailsBookViewModel(book) {
return {
title: ko.observable(book.title),
author: ko.observable(book.author),
publisher: ko.observable(book.publisher)
};
}
function LibraryUI(books) {
var bookViewModels = books.map(libraryBookViewModel);
var viewModel = {
books: ko.observableArray(bookViewModels);
};
this.renderTo = function (el) {
ko.applyBindings(viewModel, el);
};
}
function BookDetailsUI(book) {
var viewModel = detailsBookViewModel(book);
this.renderTo = function (el) {
ko.applyBindings(viewModel, el);
};
}
Note how we could make the book details appear in a jQuery UI dialog, instead of in a singleton #book-details element, by changing the showDetails function to do
var dialogEl = document.createElement("div");
detailsUI.renderTo(dialogEl);
$(dialogEl).dialog();
There are 3 frameworks out there that help with creating SPAs using Knockoutjs.
Durandal
Pagerjs
KnockBack
I have used Durandal and I really like it. Easy to use and has a lot of nice configurations so you can plug-in your own implementations. Also, Durandal is created by the same creator of Caliburn which was an very popular framework for building Silverlight/WPF applications.
Now in 2014, you probably want to use Knockout's component feature and Yeoman to scaffold your initial ko project. See this video: Steve Sanderson - Architecting large Single Page Applications with Knockout.js
[update april 5, 2013] at time of writing this answer was valid. Currently I would also suggest the Durandal JS approach as the way to go. Or check John Papa's Hot Towel or Hot Towelette SPA templates if you are using ASP.NET MVC. This also uses Durandal.
Original answer below:
I would like to point out Phillipe Monnets 4 part series about Knockout.js to you. He is the first Blogger I encounterd who splits up his example project in multiple files. I really like most of his ideas. The only thing I missed, was how to handle ajax / rest retrieved collections by using some kind of Repository / Gateway pattern. It's a good read.
Link to part 1: http://blog.monnet-usa.com/?p=354
Good luck!
I just open-sourced the mini SPA framework I put together with Knockout being the major component.
knockout-spa
A mini (but full-fledged) SPA framework built on top of Knockout, Require, Director, Sugar.
https://github.com/onlyurei/knockout-spa
Live Demo:
http://knockout-spa.mybluemix.net
Features
Routing (based on Flatiron's Director): HTML5 history (pushState) or hash.
Highly composable and reusable: pick modules/components for a page in the page-specific JS and they will be auto-wired for the page's HTML template
SEO ready (prerender.io)
Fast and lightweight (85 KB of JS minified and gizpped)
Two-tier bundle build for JS for production: common module that will be used by most pages, and page-specific modules that will be lazy-loaded
Organized folder structure to help you stay sane for organizing and reusing JS, CSS, HTML
Using Knockout 3.3.0+ so ready for Knockout's flavor of web component and custom tags (http://knockoutjs.com/documentation/component-overview.html)
All documentation are in the major dependencies' own homepages, so that you don't need to completely learn a new framework
Knockout http://knockoutjs.com
Require http://requirejs.org
Director https://github.com/flatiron/director
jQuery http://jquery.com
Sugar http://sugarjs.com

Categories