What is the difference between MVC and MVVM?

Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?

MVC/MVVM is not an either/or choice.

The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.

For ASP.Net, MVVM is used to two-way bind data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns on the server-side.

For Silverlight and WPF, the MVVM pattern is more encompassing and can appear to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the ViewModel simply replaced the controller in MVC (as if you could just substitute VM for C in the acronym and all would be forgiven)...

The ViewModel does not necessarily replace the need for separate Controllers.

The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly no idea where its data is coming from.

*Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.

Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.

From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind to make XAML editing a more independent task. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.

The basic MVCVM guidelines we follow are:

  • Views display a certain shape of data. They have no idea where the data comes from.
  • ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
  • Models hold the actual data (various context, store or other methods)
  • Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.

We also noted that the Sculpture code-gen framework implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.

Don't assume controllers are made obsolete by View-models.

I have started a blog on this topic which I will add to as and when I can. There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.

An additional benefit of using an MVCVM model is that only the controller objects need to exist in memory for the life of the application and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.

Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try avoid people replacing controllers with ViewModels

JavaScript object operations – How to add / remove item from a JavaScript object

Getting into JavaScript frameworks like vue.js and react.js, now it's time to review some of the JavaScript fundamentals.

 

How to remove item from a JavaScript object

Say I create an object as follows:

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};

What is the best way to remove the property regex to end up with new myObject as follows?

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI"
};
var test = {'red':'#FF0000', 'blue':'#0000FF'};
delete test.blue; // or use => delete test['blue'];
console.log(test);

this deletes test.blue

 

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 
How do I add a property to a JavaScript Object using a variable as the name?

You can use this equivalent syntax:

obj[name] = value;
 
How do I check if an object has a key in JavaScript? 

http://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

Try the javascript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if keyis available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key')produces the result most code is looking for.

 

You'll have to iterate:

for (var k in obj) {
  if (!obj.hasOwnProperty(k)) continue;
  if (obj[k] === "orange") {
    /* yaay! an orange! */
  }
}

Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That might not be desirable in some cases, and really it's one of the things you kind-of need to understand in order to know for sure whether you do or don't want to make that test. Properties that you pick up from an object's prototype can sometimes be things dropped there by various libraries. (I think the ES5 standard provides for ways to control whether such properties are "iterable", but in the real world there's still IE7.)

 

11.2.1 Property Accessors

I want to use the value of an objects property to name the property of another object. Easy to do in PHP:

$object1->property = 'name';
$object2->{$object1->property} = "value";
echo $object2->name; //outputs "value"

But in Javascript I can't figure out how to do this. The curly braces are used a different way.

Anyone know the php equivalent in javascript?

Thanks 🙂

object2[object1.property] = "value";

 

obj[type]

You use subscript notation.

11.2.1 Property Accessors

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName
CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]
CallExpression [ Expression ]

Change paste to paste and indent in sublime text 2/3

Change paste to paste and indent in sublime text 2/3:

Go to Sublime's menu -> preferences -> 'Key Bindings' -> edit the user preference file to add the below:

[
    { "keys": ["ctrl+shift+v"], "command": "paste" },
    { "keys": ["ctrl+v"], "command": "paste_and_indent" }
]

This will turn ctrl+v to paste and indent instead of the default paste.

 

 

OctoberCMS RESTful API plugins

API Generator

Generates RESTful APIs using available models

RESTful API

RESTful API (WebService) for Import/Export Operations with Extended Features

RESTful

Create RESTful APIs with ease

You can start building your custom REST API based on these plugins.

Emmet LiveStyle – live CSS style editing in Chrome via Sublime Text [highly recommended]

This is one of the best live css extension to use with sublime text editor, live css preview and more.
LiveStyle — the first bi-directional real-time edit tool for CSS, LESS and SCSS.
Instantly updates your web-page stylesheet while you edit CSS, LESS or SCSS file in your text editor. No file saving or page reloading: pure real-time experience! And this is the first tool that transfers updates from DevTools back into source code the right way.

Includes Remote View: creates publicly-available URL (aka “reverse tunnel”) to test your local web-sites on any internet-connect device or services like BrowserStack.

 

 

 

My Brackets extension list

Here is my list of brackets extensions for productivity.  http://brackets.io/

Animations deactivatorAlexander Taratin 1.0.0

1279

Disable animations for better perfomance

More info…

Auto console.log generatorBorja Guzman 0.2.6

5962

Allows you to console.log a var with a simple shortcut

More info…

beautify.iodingdong (https://github.com/dingdong-io)1.2.1

167417

Format JavaScript, HTML, and CSS files

More info…

Brackets Additional Right Click MenuDeddy Lasmono Putro 0.5.1

21548

A Brackets extension that add additional functionality to Brackets editor right menu, like cut, copy, paste, select all, Camel Case, UPPERCASE, lowercase, fix indentation and some functionality from ...

More info…

Brackets GitMartin Zagora0.16.6

447216

Integration of Git into Brackets

More info…

Translated into 7 languages, including yours

Brackets PreferencesKonrad Lipner1.0.0

12491

Preferences editor for Brackets. Display/edit all preferences. Have regex search for preference.

More info…

Brackets SASSJason San Jose (https://github.com/jasonsanjose)2.0.5

13545

***IMPORTANT*** Read "More info..." if you have issues removing or installing. Compiles SASS *.sass/*.scss files when changed. Updates styles during Live Preview. Experimental support for Quick Edit.

More info…

Brackets SASS Code HintsAmin Ullah Khan (https://github.com/sprintr)0.1.0

16586

Provides code hints for SASS documents

More info…

Brackets Sass HintsKamil Armatys (https://github.com/karmatys)1.0.3

7737

An extension for Brackets to show SASS hints in the code editor.

More info…

Brackets ToolsYasin Kuyu 0.2.0

44436

Brackets developer tools extension

More info…

Translated into 8 languages, including yours

Brackets TwigAthorcis (https://github.com/Athorcis)1.1.3

12914

Highlight Twig syntax inside HTML files

More info…

Translated into 2 languages, including yours

brackets-compareHubert B Manilla0.2.7

28853

A diff tool for brackets

More info…

BracketstoIXApptoIX Limited 3.3.0

49203

[3.0]Execute,Lorem ipsum, Break Line, Recent Files.Change(Case, Quote, Slash, Tab, Encoding), Sort, (Un)Tag, Clipboard, Internet, (Minify, traceur, sass, compass), Text Replace, Extrators, JSLint ...

More info…

Translated into 3 languages, including yours

ConsoleAlexandru Ghiura1.4.1

22333

Shows console.log & console.error & console.warn without developer tools.

More info…

copycaseAnoop Elias 0.0.1

3194

CopyCase plugin for brackets enable copying text in snake-case to CamelCase and vice-versa, useful for angular developers
Delkos Dark ThemeDavid Sánchez i Gregori0.0.5

33948

A dark, elegant, easy readable theme.

More info…

File Info to ClipboardVince Malone 1.1.0

4168

Copy name, path and directory path of a file to the clipboard.

More info…

FuncDocrOle Kröger 0.8.41

85723

Generates JSDoc,PHPDoc annotations for your functions.

More info…

Indent GuidesLance Campbell (https://github.com/lkcampbell)1.3.7

211281

Show indent guides in the code editor.

More info…

JS CSS MinifierAndrew Bagshaw2.0.0

64092

Easily minify single files or all files in a project. Also includes concatenation features as well as auto-minification on save.

More info…

Translated into 6 languages, including yours

JSHintRaymond Camden (http://www.raymondcamden.com)2.2.20

220503

Adds JSHint support to Brackets.

More info…

Magento 2 HintRafael Corrêa Gomes0.1.0

3235

Ideal for developing Magento 2 themes, get hints of the main functions, classes and methods.

More info…

Translated into 6 languages, including yours

MinimapSenko Anton 3.2.6

90893

The minimap shows a smaller version of your code at the right of the screen. It can be used to quickly scroll to a certain part of your file. This is a fork of brackets-wdminimap by Brian Adams ...

More info…

Paste and IndentAndrew Huth (https://github.com/ahuth)0.2.0

49753

Automatically apply the correct indentation to pasted text

More info…

Permanent ScrollbarsMatt Stow matt@mattstow.com (http://mattstow.com)0.1.0

2410

Makes the file list scrollbars always visible

More info…

PHP Code Quality ToolsMikael Jorhult (http://jorhult.se)0.1.11

69495

Analyze and lint PHP using several code analysis tools. Please note that this extension needs PHP to be installed on your machine to work properly.

More info…

Translated into 5 languages, including yours

PHP SmartHintsAndrew MacKenzie (https://github.com/mackenza)1.2.2

114141

Provides code hints for PHP files including PHP keywords, built-in functions, constants and variables. Also provides hinting for variables in the current open PHP document. Note that this is a ...

More info…

Translated into 4 languages, including yours

PHPLinter for BracketsSerghei1.0.2

13861

This extension works using `php -l` command
Pretty JsonStephen Keep (https://github.com/stephenkeep/)0.1.2

24109

Make Your Json Pretty and Linted, turn a single line of json into multiple lines with ctrl+shift+J

More info…

SASS/SCSS HintsKonstantin Kobs1.2.0

10112

Autocompletion for SASS/SCSS variables and mixins. Color previews included. Forked and updated from: https://github.com/konstantinkobs/brackets-SASShints

More info…

Select Tag ContentsMatthew Seiler 1.0.3

7941

Provides a shortcut (Ctrl/Cmd+Shift+A) for selecting all content between tags in HTML, PHP, XML

More info…

Show WhitespaceDennis Kehrig (https://github.com/DennisKehrig)2.0.1

39215

Visualizes whitespace similar to how Sublime Text does it

More info…

Smarty Syntax HighlightingJeremy Lee (https://github.com/JeremyLee)1.0.0

4891

Enables the built-in Smarty syntax highlighting for the .tpl file type.

More info…

Strip trailing spacesRosen Stoyanov (http://pockata.org)1.3.0

8675

A Brackets extension to strip traling whitespace at the end of the line on document save.

More info…

Tab To SpaceDavid Deraedt (http://www.dehats.com)1.0.0

12800

Converts indentation to tabs or spaces.

More info…

Various improvementsDammmien2.2.1

27999

Add more informations in the status bar, lowercase and uppercase converter, super clipboard, button close all folders in file tree, files search

More info…

White Space SanitizerMiguel Castillo 1.2.1

27523

Bring sanity to your white spaces and tabs leveraging Brackets settings

More info…

Whitespace NormalizerDimitar Bonev (https://github.com/dsbonev/)0.3.0

30850

trims trailing whitespaces; transforms tabs to spaces; adds newline at the end of file

More info…