MVP pattern with Javascript framework? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 months ago.
The community reviewed whether to reopen this question 6 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Has anyone been able to implement the MVP model with any javascript frameworks? I'm having trouble figuring out how to have the presenter -> view inversion from server code to javascript. I have some ideas, but kind of hackish and would like to see what others are doing.

The main goal with MVP is decoupling of different aspects in the code. Normally, in JavaScript, there are 3 major such aspects:
Event Handling
DOM manipulation
Server communication (AJAX calls)
For each of these concerns, there's a corresponding term from MVP:
EventHandling = Presenter
DOM Manipulation = View
AJAX calls = Model
Since indeed it is not always simple to implement the 3 aspects, an EVENT BUS may come in handy. This bus should be a singleton and all the events, raised in various context should be published on the bus. The Presenter needs to register to its events and react accordingly when events happen.
Here is how it would work:
First thing that happens is the page load. Listen to this using the normal event model or jQuery or whatever is convenient. Create the Model, the View and the Presenter. The Presenter needs to hold the View and Model instances since he's gonna use them.
var model = new Model();
var view = new View();
var presenter = new Presenter(model, view);
Remember that Presenter is the event handler so the bus should know about it and route events to it for handling:
bus.registerHandler(presenter);
The first event is the "init", which means the page has loaded and the MVP objects are all set:
bus.init(); // call this yourself
This would trigger something in the Presenter, like a function. I prefer the on... naming convention, in this example presenter.onInit(). This gives a chance to install UI listeners:
// in the Presenter
onInit: function() {
view.addSubmitListener();
view.addWhateverListener();
...
}
// in the View (using jQuery)
addSubmitListener: function() {
$("#submitButton").click(function() {
var formData = ...
bus.submit(formData); // publish an event to the bus
});
}
When the Submit button is clicked the bus.submit(formData) is called and this will route it to the handler -- presenter.onSubmit(formData):
// in the Presenter
onSubmit: function(formData) {
model.postForm(formData, function(data) {
// handle the response
view.updateSomething(data);
});
}
And so on... The entire trick is binding the bus to the presenter and then you're in the loop.

My vote goes to Backbone.js. Even docs says it is MVC, I would say it is MVP.
VIEW = html template (jQuery.template)
MODEL = Backbone.Model
PRESENTER = Backbone.View ( layer between your view-tempate and how to bound data to it, and more thins you can do) and what is best you can use in render method couple views (html templates) or switch which to use...
and what is best you still have controller
CONTROLLER = Backbone.Controller
Alternative could be as #JoshRivers mentioned, knockoutJS but my personal opinion is that view template is overwhelmed with binding stuff.
And last note. Thing is View as V from either MVC or MVP is something which can be built from your template without coding it, make good HTML template parser and you are good to go :) Believe me, convention is your friend.

Another one, for jQuery folks: http://javascriptmvc.com/
Just a note that Ext JS also supports the MV(x) pattern since version 4.0, which I'll mention as an ex-Ext person. Like most frameworks, they too call it "MVC" (as does most everyone in the JS world, see TodoMVC, as opposed to TodoMVP). However from a practical standpoint, the tools are there in Ext to implement the C/P portion of the pattern as best fits your needs. Patterns are useful, but like most anything, can limit your thinking when treated dogmatically.

Related

difference between angular js and java script [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Please Reply
- what is the role of angular js?
- what is the role of java script?
- when use angularjs
- when use java script
- which one is powerfull
Angular and jQuery are both libraries/frameworks written in Javascript. Asking for me to compare Angular to Javascript is like asking for a comparison between bread and flour.
However, the browser APIs for DOM manipulation are implemented with a fundamentally different idea to Angular, so I'm going to assume that this is what your assignment is expecting you to identify.
The key point to focus on is that the paradigm is fundamentally different. Angular takes a declarative approach, whereas both the DOM and jQuery are imperative.
Declarative
A style of building the structure and elements of computer programs, that expresses the logic of a computation without describing its control flow. [1]
A declarative language is one in which you describe what you want, not how it should be done. This is very much Angular's approach with directives.
Imperative
[A style] in which algorithms are implemented in terms of explicit steps. [1]
When we write code using the DOM APIs or jQuery, we have to detail the "how" of the process.
Let's take data binding as an example. We want to bind a value from a text input, into a label.
With the DOM
<input type='text' id='bind-input'>
<label id='bind-output'></label>
And our Javascript:
window.addEventListener('load', function() {
var input = document.getElement('bind-input'),
output = document.getElement('bind-output');
input.addEventListener('change', function() {
output.innerText = input.value;
});
});
We have to very specifically explain what we need the browser to do. We have to listen to certain events, make sure that the DOM is loaded, keep track of our element's IDs, all just to update our label whenever our input changes.
With jQuery
<input type='text' id='bind-input'>
<label id='bind-output'></label>
We still need some Javascript:
$(document).ready(function() {
var $input = $('#bind-input'),
$output = $('#bind-output');
$input.on('change', function() {
$output.html($input.value());
});
});
As you can see, this is pretty similar to the DOM approach. We have to explain to the browser exactly what we want it to do.
With Angular
<input type='text' ng-model='bound'>
<label ng-bind='bound'></label>
We don't even need to write any code for this to work with Angular! (Obviously we'd need an empty controller somewhere, but you get the idea).
The declarative approach is primarily a way for us to abstract away from the implementation details. Angular directives make it very easy to wrap up these common behaviours into small reusable components than can be applied to our HTML in a declarative way.

MVVM: Should the viewModel be architectured like the view or like the model [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In our KnockoutJS project (a MVVM data-binding library) we have two types of viewModel that collides.
On one hand, we have viewModels that are architectured like the view. So let's say I have a form that allow me to create a user, it's a formVM. And each property of the viewModel is a property of the form. Each property is a computed that will write on the business model.
On the other hand, we have viewModels that are architectured like the business model. In our previous example, it would be a userVM, with the basic properties of the model plus other such as a label that is calculated from the username etc. And in the view html, we use here userVM.label for instance.
Is one more correct than the other? Which one do you use?
I would say both are incorrect. There definetly shouldn't be any business logic in your viewmodels. This logic belongs in your business layer. The viewmodel should just hold a model (with observables bound to your form fields) and pass it to the business layer whenever appropriate.
Strictly speaking I'd say the viewmodel should only contain the model for your view (observables), event handlers, and very little else. When the user interacts with the UI, your event handlers will gather the necessary information and pass it to the business layer. This business layer might return data for the view, such as a calculated label that you mentioned. This value can then be inserted into a 'dumb' observable and therefore be displayed in the view without any business logic going into your viewmodel.
When the user hits save, you grab the data from the observables and pass it to the business layer, which will respond (changes saved succesfully, or something went wrong). The viewmodel can use this response to update the UI.
So in short, the viewmodel handles what the UI shows, and handles any interaction done by the user. But it typically only contains dumb functionality to pass the info along to the modules that contain the intelligence.
That's my view, and to be honest: in practise I violate this principe quite often myself.

Move from 2005 Javascript spaghetti code to modular Javascript of 2013? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have inherited a legacy JS multi page application and am contemplating the idea of migrating its code to modern day modular Javascript :
implement loose coupling
implement a modular system
Actually it seems a lot easier to start a new project using these techniques than to migrate an old style one.
What I have right now is stuff along the lines of
...
Click this !
...
and in a JS file a global function without any context, called DoSomething.
I read a lot about loose coupling and modular JS, but somehow I wonder how to actually implement stuff like my silly example, because it doesn't seem to have any context, and then that attaching all simple button/link actions through events and loose coupling makes it harder to read code and find out what a simple action command does.
How youd you actually implement this kind of thing, assuming there is a huge amount of such links and global functions everywhere ?
EDIT : I should have been more clearer, sorry.
Actually I can not use any JS-generated DOM technique such as Backbone views and so on, because all my HTML is generated server-side (it is mandatory in this app unfortunately) so the question remains as to how to efficienty come up with modules and such code, if most of what they do is respond to DOM events (on specific pre-defined elements generated server-side) and send data back to the server in form of page changes or AJAX calls.
For utility-like modules or other stuff decoupled from the DOM, it's quite clear how to implement modules, but for stuff tied to a static DOM that JS does not generate ?
Specifically, where and how to implement event handers, triggers changing DOM elements ? and so on.
I had to do this in 2013 and it was a major undertaking. RequireJS gives you the ability to separate your modules into separate files (if you want) where the dependencies are clearly laid out. Backbone can give you some structure for breaking things into models and views (and your own control classes). Underscore templating will let you make clean HTML templates that can be populated by a model's data.
The real answer is that you have to think like you would in a more traditional OOP language. For instance a mediator pattern allows your modules to talk to each other while remaining decoupled.
If you have a Click this div on your page and a corresponding click listener in the javascript that would now live where the Click this div is in a simple template like:
<div id="myTarget">Click this</div>
While the main page might have something like:
<div id="myApp"></div>
Your Click This view might attach to #myApp and populate it with the contents of your simple template.
A backbone view which does this might look like:
var myView = Backbone.View.extend({
el: "#myApp",
events: {
"click #myTarget" : "handleClick"
},
handleClick : function(){
// do something
},
render : function(){
this.$el.html(myTemplate);
}
});
Rinse and repeat for the various things you need to populate your page with.

What are the components of a JavaScript Browser Side Framework/Solution Architecture? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
What are the components of a JavaScript browser side web application architecture? I am aware of the following items and looking to for the most complete list.
Normalized DOM API that behaves the same in all browsers.
Ajax Wrapper offering a better API to access the XHR object.
Template engine to make writing widgets easier.
Module loading system.
... etc?
What are essential components of a client side JavaScript Architecture for building complex web apps?
The list you provided is pretty good. Here's some additional considerations
1) A good framework has good file structure and namespacing practices. One way that I am particularly fond of organizing your library might have the following files/paths:
a. projectRoot/js/lib/ams/xml/Document.js
b. projectRoot/js/lib/ams/util/util.js
c. projectRoot/js/lib/ams/util/base64.js
d. projectRoot/js/lib/ams/util/HashMap.js
Which would define the following classes and namespaces
a. ams.xml.Document: Class definition
b. ams.util: Namespace definition. Use this file to put functions on a NS, such as ams.util.toArray(). Technically, this could/should go right in the 'ams' folder, but since there are other things on the 'util' namespace, a folder is created. For an example of a namespace definition without
c. ams.util.base64: Namespace definition. Use this file to put functions on a NS, such as ams.util.base64.encode(). Since there are no namespaces below base64, no folder is necessary.
d. ams.util.HashMap: Class definition on the util namespace
2) Standardize the way you define classes to assist with inheritance. I personally prefer the psuedo-classica model with prototypal inheritance, with the use of an inheritance helper function such as:
ns.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superclass = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
this would be used as such:
ns.BaseClass = function(arg){
this._privateProp = arg;
};
ns.BaseClass.prototype._privateProp = null;
ns.Class = function(arg1, arg2){
ns.Class.superclass.constructor.call(this, arg1);
this.publicProp = arg2;
};
ns.inherits(ns.Class, ns.BaseClass)
ns.Class.prototype.publicProp = null;
3) Definitely get a good module loading system in place. You do not want to have to maintain a flat list of javascript files and their dependencies. A good one to use is in google's "closure library". It might take a bit to get set up, but it's well worth the effort. Check out "plovr" to make development with closure a bit easier. The beauty with closure is that there is a compiler which lets you create a static js file with the dependencies resolved, and the files concatenated and minified. The syntax is nice too, for instance continuing from 2) above:
in ./ns/Class.js
goog.provide('ns.Class');
goog.require('ns.BaseClass');
ns.Class = function(arg1, arg2){
...
The closure framework will also make sure that 'ns' exists before you try to define 'Class' on it ( since it knows you are going to provide ns.Class), thus preventing a null object error.
4) If you are planning on putting a lot of logic on the client, you should think about creating some form of model class to assist with synchronization of your view with the back-end server state. A lot of people refer to this as MVC, but that is a bit of a misnomer as it typically refers to a system based around PHP and static page generation. For more modern complex javascript-based web apps, an MVVM structure is more appropriate.
5) Depending on how much html creation you want the framework to be responsible for, if you plan on creating things like Containers, Panels, Buttons, etc, you might want to build your own event system which skips the DOM. Imagine you had a base Panel class, which provided additional functionality around a simple DIV. Then you called Panel::add and gave it an instance of a Button (which managed a BUTTON or a DIV with click handlers - same thing). You might want to dispatch an 'add' event from the panel, but there is no need for the DOM if you want to do that. Only other instances of your framework would know how to handle the 'add' anyways. In reality, you probably only need to capture the DOM events (maybe make a domEvent util...) and then dispatch events within your framework. Why would you do this? SPEED and control. Dom events are bulky, expensive, and behave differently from one browser to the next. Besides, it's nice to be able to express events in a way that is not tied to the DOM
6) Think about the difference between your framework (which presumably will be shared across several projects) and a project using it. They probably should have different namespaces and file structure. Following the namespaceing conventions above would leave you with something like
projectRoot/js/src/app/MainPanel.js
projectRoot/js/src/app/ViewPort.js
projectRoot/js/src/app/...
Hope all this helps. Good luck!

what is MVVM, and should we use it? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've been looking at the MVVM pattern, specifically knockoutjs, and mostly it just makes me cringe. I won't go on a long rant about the benefits of keeping structure, presentation and display separate, I'll just ask (as an example): What's the difference between
<button data-bind="click: someJavaScriptFunction">Something</button>
and
<button onclick="someJavaScriptFunction();">Something</button>
and should we be putting so much behavior control into the markup? As clean and as minimalistic as this is, it seems to go against every web programming tenet I've ever heard about.
Am I wrong?
Here's a more direct answer to your question.
In the second example, you are referring to a function that has to be in the global scope (i.e. a property of the window object).
In the first example, you are referring to a property of the current view model.
Yes, it's a subtle distinction, but it is an important one. If you use on-event attributes you can only refer to things that exist in the global scope. This means you have to put everything you want to access in the global scope, which leads to very messy code.
If you use declarative bindings, the exact meaning of the bindings instead depends on the context.
It helps to think about the HTML markup as more coincidental. What you are really looking at is structured access to the view model. Think of with and forEach as nested contexts and of the other bindings as their attributes. The relationship between the declarative bindings and the underlying HTML suddenly feels more like working with XSLT.
The two examples look very similar. But the underlying concepts are vastly different and are what makes data binding so powerful and on-event attributes so obnoxious.
The reason on-event attributes are frowned upon isn't just that they mix logic with structure. It's that they're a weak attempt to bolt arbitrary JavaScript code to HTML elements which prevents proper encapsulation of application logic. On-event attributes are low-level "hooks", bindings extend the behaviour of elements.
All that said, it is likely possible to do the same horrible things people have done with on-event attributes by using declarative bindings. The difference is in what else you can do with them. You shouldn't always judge technologies by how they can be abused -- we're all adults here.
Your only using one part of MVVM - specifically the View - in that code example you gave above. The reason to use Knockout (or any other MVVM library) is to make it easy to bind your views to a Model - a View Model - thus allowing you stop writing a lot of boilerplate code just to return values from your view.
I see a lot of wonky javascript/jquery code where people go and use something like this:
var ex = {
some1: $('#textbox1').val(),
some2: $('#textbox2').val()
};
The problem with this is that it is literally littered throughout the web application and it becomes extremely tedious to maintain. I know with Knockout, whenever my View is updated, my View Model will be updated as well.
It's not needed for every application, and you shouldn't use it just because it's whats "cool" to use. There obviously needs to be a reason to use it, my example above is one reason and im sure there are more.

Categories

Resources