permalink

29

Understanding MVVM – A Guide For JavaScript Developers

MVVM (Model View ViewModel) is an architectural pattern based on MVC and MVP, which attempts to more clearly separate the development of user-interfaces (UI) from that of the business logic and behaviour in an application. To this end, many implementations of this pattern make use of declarative data bindings to allow a separation of work on Views from other layers.

This facilitates UI and development work occurring almost simultaneously within the same codebase. UI developers write bindings to the ViewModel within their document markup (HTML), where the Model and ViewModel are maintained by developers working on the logic for the application.

History

MVVM was originally defined by Microsoft for use with Windows Presentation Foundation (WPF) and Silverlight, having been officially announced in 2005 by John Grossman in a blog post about Avalon (the codename for WPF). It also found some popularity in the Adobe Flex community as an alternative to simply using MVC.

In recent years, MVVM has been implemented in JavaScript in the form of structural frameworks such as KnockoutJS, Kendo MVVM and Knockback.js, with an overall positive response from the community.

Let’s now review the three components that compose MVVM.

Model

As with other members of the MV* family, the Model in MVVM represents domain-specific data or information that our application will be working with. A typical example of domain-specific data might be a user account (e.g name, avatar, e-mail) or a music track (e.g title, year, album).

Models hold information, but typically don’t handle behaviour. They don’t format information or influence how data appears in the browser as this isn’t their responsibility. Instead, formatting of data is handled by the View, whilst behaviour is considered business logic that should be encapsulated in another layer that interacts with the Model – the ViewModel.

The only exception to this rule tends to be validation and it’s considered acceptable for Models to validate data being used to define or update existing models (e.g does an e-mail address being input meet the requirements of a particular Regular expression?).

In KnockoutJS, Models fall under the above definition, but often make Ajax calls to a server-side service to both read and write Model data.

If we were constructing a simple Todo application, a KnockoutJS Model representing a single Todo item could look as follows:

var Todo = function (content, done) {
    this.content = ko.observable(content);
    this.done = ko.observable(done);
    this.editing = ko.observable(false);
};

Note: You may notice in the above snippet that we are calling a method observables() on the KnockoutJS namespace ko. In KnockoutJS, observables are special JavaScript objects that can notify subscribers about changes and automatically detect dependencies. This allows us to syncronize Models and ViewModels when the value of a Model attribute is modified.

View

As with MVC, the View is the only part of the application of users actually interact with. They are an interactive UI that represent the state of a ViewModel. In this sense, MVVM View is considered active rather than passive, but what does this mean?.

A passive View has no real knowledge of the models in our application and is manipulated by a controller. MVVM’s active View contains the data-bindings, events and behaviours which require an understanding of the Model and ViewModel. Although these behaviours can be mapped to properties, the View is still responsible for handling events to the ViewModel.

It’s important to remember the View isn’t responsible here for handling state – it keeps this in sync with the ViewModel.

A KnockoutJS View is simply a HTML document with declarative bindings to link it to the ViewModel. KnockoutJS Views display information from the ViewModel, pass commands to it (e.g a user clicking on an element) and update as the state of the ViewModel changes. Templates generating markup using data from the ViewModel can however also be used for this purpose.

To give a brief initial example, we can look to the JavaScript MVVM framework KnockoutJS for how it allows the definition of a ViewModel and it’s related bindings in markup:

ViewModel:

var aViewModel = {
    contactName: ko.observable('John');
};

View:

<input id="source" data-bind="value: contactName, valueUpdate: 'keyup'" /></p>
<div data-bind="visible: contactName().length > 10">
    You have a really long name!
</div>

Our input text-box (source) obtains it's initial value from contactName, automatically updating this value whenever contactName changes. As the data binding is two-way, typing into the text-box will update contactName accordingly so the values are always in sync.

Although implementation specific to KnockoutJS, the <div> containing the 'You have a really long name! text also contains simple validation (once again in the form of data bindings). If the input exceeds 10 characters, it will display, otherwise it will remain hidden.

Moving on to a more advanced example, we can return to our Todo application. A trimmed down KnockoutJS View for this, including all the necessary data-bindings may look as follows.

<div id="todoapp">
    <header>
        <h1>Todos</h1>
        <input id="new-todo" type="text" data-bind="value: current, valueUpdate: 'afterkeydown', enterKey: add"
               placeholder="What needs to be done?"/>
    </header>
    <section id="main" data-bind="block: todos().length">
        <input id="toggle-all" type="checkbox" data-bind="checked: allCompleted">
        <label for="toggle-all">Mark all as complete</label>
        <ul id="todo-list" data-bind="foreach: todos">
           <!-- item -->
            <li data-bind="css: { done: done, editing: editing }">
                <div class="view" data-bind="event: { dblclick: $root.editItem }">
                    <input class="toggle" type="checkbox" data-bind="checked: done">
                    <label data-bind="text: content"></label>
                    <a class="destroy" href="#" data-bind="click: $root.remove"></a>
                </div>
                <input class="edit" type="text"
                       data-bind="value: content, valueUpdate: 'afterkeydown', enterKey: $root.stopEditing, selectAndFocus: editing, event: { blur: $root.stopEditing }"/>
            </li>
        </ul>
    </section>
</div>

Note that the basic layout of the mark-up is relatively straight-forward, containing an input textbox (new-todo) for adding new items, togglers for marking items as complete and a list (todo-list) with a template for a Todo item in the form of an li.

The data bindings in the above markup can be broken down as follows:

 

  • The input textbox new-todo has a data-binding for the current property, which is where the value of the current item being added is stored. Our ViewModel (shown shortly) observes the current property and also has a binding against the add event. When the enter key is pressed, the add event is triggered and our ViewModel can then trim the value of current and add it to the Todo list as needed
  • The input checkbox toggle-all can mark all of the current items as completed if clicked. If checked, it triggers the allCompleted event, which can be seen in our ViewModel
  • The item li has the class done. When a task is marked as done, the CSS class editing is marked accordingly. If double-clicking on the item, the $root.editItem callback will be executed
  • The checkbox with the class toggle shows the state of the done property
  • A label contains the text value of the Todo item (content)
  • There is also a remove button that will call the $root.remove callback when clicked.
  • An input textbox used for editing mode also holds the value of the Todo item content. The enterKey event will set the editing property to true or false

 

ViewModel

The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.

For example, let us imagine that we have a model containing a date attribute in unix format (e.g 1333832407). Rather than our models being aware of a user's view of the date (e.g 04/07/2012 @ 5:00pm), where it would be necessary to convert the address to it's display format, our model simply holds the raw format of the data. Our View contains the formatted date and our ViewModel acts as a middle-man between the two.

In this sense, the ViewModel might be looked upon as more of a Model than a View but it does handle most of the View's display logic.The ViewModel may also expose methods for helping to maintain the View's state, update the model based on the action's on a View and trigger events on the View.

In summary, the ViewModel sits behind our UI layer. It exposes data needed by a View (from a Model) and can be viewed as the source our Views go to for both data and actions.

KnockoutJS interprets the ViewModel as the represtation of data and operations that can be performed on a UI. This isn't the UI itself nor the data model that persists, but rather a layer that can also hold the yet to be saved data a user is working with. Knockout's ViewModels are implemented JavaScript objects with no knowledge of HTML markup. This abstract approach to their implementation allows them to stay simple, meaning more complex behaviour can be more easily managed on-top as needed.

A partial KnockoutJS ViewModel for our Todo application could thus look as follows:

// our main ViewModel
    var ViewModel = function (todos) {
        var self = this;
    // map array of passed in todos to an observableArray of Todo objects
    self.todos = ko.observableArray(ko.utils.arrayMap(todos, function (todo) {
        return new Todo(todo.content, todo.done);
    }));
    // store the new todo value being entered
    self.current = ko.observable();
    // add a new todo, when enter key is pressed
    self.add = function (data, event) {
        var newTodo, current = self.current().trim();
        if (current) {
            newTodo = new Todo(current);
            self.todos.push(newTodo);
            self.current("");
        }
    };
    // remove a single todo
    self.remove = function (todo) {
        self.todos.remove(todo);
    };
    // remove all completed todos
    self.removeCompleted = function () {
        self.todos.remove(function (todo) {
            return todo.done();
        });
    };
    // writeable computed observable to handle marking all complete/incomplete
    self.allCompleted = ko.computed({
        //always return true/false based on the done flag of all todos
        read:function () {
            return !self.remainingCount();
        },
        //set all todos to the written value (true/false)
        write:function (newValue) {
            ko.utils.arrayForEach(self.todos(), function (todo) {
                //set even if value is the same, as subscribers are not notified in that case
                todo.done(newValue);
            });
        }
    });
    // edit an item
    self.editItem = function(item) {
        item.editing(true);
    };
 ..

Above we are basically providing the methods needed to add, edit or remove items as well as the logic to mark all remaining items as having been completed Note: The only real difference worth noting from previous examples in our ViewModel are observable arrays. In KnockoutJS, if we wish to detect and respond to changes on a single object, we would use observables. If however we wish to detect and respond to changes of a collection of things, we can use an observableArray instead. A simpler example of how to use observables arrays may look as follows:

// Define an initially an empty array
var myObservableArray = ko.observableArray();
// Add a value to the array and notify our observers
myObservableArray.push(‘A new todo item’);

Note: The complete Knockout.js Todo application we reviewed above can be grabbed from TodoMVC if interested.

Recap: The View and the ViewModel

Views and ViewModels communicate using data-bindings and events. As we saw in our initial ViewModel example, the ViewModel doesn’t just expose Model attributes but also access to other methods and features such as validation.

Our Views handle their own user-interface events, mapping them to the ViewModel as necessary. Models and attributes on the ViewModel are syncronized and updated via two-way data-binding.

Triggers (data-triggers) also allow us to further react to changes in the state of our Model attributes.

Recap: The ViewModel and the Model

Whilst it may appear the ViewModel is completely responsible for the Model in MVVM, there are some subtleties with this relationship worth noting. The ViewModel can expose a Model or Model attributes for the purposes of data-binding and can also contain interfaces for fetching and manipulating properties exposed in the view.

Pros and Cons

You now hopefully have a better appreciation for what MVVM is and how it works. Let’s now review the advantages and disadvantages of employing the pattern:

Advantages

  • MVVM Facilitates easier parallel development of a UI and the building blocks that power it
  • Abstracts the View and thus reduces the quantity of business logic (or glue) required in the code behind it
  • The ViewModel can be easier to unit test than event-driven code
  • The ViewModel (being more Model than View) can be tested without concerns of UI automation and interaction

Disadvantages

  • For simpler UIs, MVVM can be overkill
  • Whilst data-bindings can be declarative and nice to work with, they can be harder to debug than imperative code where we simply set breakpoints
  • Data-bindings in non-trivial applications can create a lot of book-keeping. You also don’t want to end up in a situation where bindings are heavier than the objects being bound to
  • In larger applications, it can be more difficult to design the ViewModel up front to get the necessary amount of generalization

MVVM With Looser Data-Bindings

It’s not uncommon for JavaScript developers from an MVC or MVP background to review MVVM and complain about it’s true separation of concerns. Namely, the quantity of inline data-bindings maintained in the HTML markup of a View.

I must admit that when I first reviewed implementations of MVVM (e.g KnockoutJS, Knockback), I was surprised that any developer would want to return to the days of old where we mixed logic (JavaScript) with our markup and found it quickly unmaintainable. The reality however is that MVVM does this for a number of good reasons (which we’ve covered), including faciltiating designers to more easily bind to logic from their markup.

For the purists among us, you’ll be happy to know that we can now also greatly reduce how reliant we are on data-bindings thanks to a feature known as custom binding providers, introduced in KnockoutJS 1.3 and available in all versions since.

KnockoutJS by default has a data-binding provider which searches for any elements with data-bind attributes on them such as in the below example.

<input id="new-todo" type="text" data-bind="value: current, valueUpdate: 'afterkeydown', enterKey: add" placeholder="What needs to be done?"/>

When the provider locates an element with this attribute, it parses it and turns it into a binding object using the current data context. This is the way KnockoutJS has always worked, allowing you to declaratively add bindings to elements which KnockoutJS binds to the data at that layer.

Once you start building Views that are no longer trivial, you may end up with a large number of elements and attributes whose bindings in markup can become difficult to manage. With custom binding providers however, this is no longer a problem.

A binding provider is primarily interested in two things:

  • When given a DOM node, does it contain any data-bindings?
  • If the node passed this first question, what does the binding object look like in the current data context?.

Binding providers implement two functions:

  • nodeHasBindings: this takes in a DOM node which doesn’t necessarily have to be an element
  • getBindings: returns an object representing the bindings as applied to the current data context

A skeleton binding provider might thus look as follows:

var ourBindingProvider = {
    nodeHasBindings: function(node) {
        // returns true/false
    },
    getBindings: function(node, bindingContext) {
        // returns a binding object
    }
};

Before we get to fleshing out this provider, let’s briefly discuss logic in data-bind attributes.

If when using Knockout’s MVVM you find yourself dissatisfied with the idea of application logic being overly tied into your View, you can change this. We could implement something a little like CSS classes to assign bindings by name to elements. Ryan Niemeyer (of knockmeout.net) has previously suggested using data-class for this to avoid confusing presentation classes with data classes, so let’s get our nodeHasBindings function supporting this:

// does an element have any bindings?
function nodeHasBindings(node) {
    return node.getAttribute ? node.getAttribute("data-class") : false;
};

Next, we need a sensible getBindings() function. As we’re sticking with the idea of CSS classes, why not also consider supporting space-separated classes to allow us to share binding specs between different elements?.

Let’s first review what our bindings will look like. We create an object to hold them where our property names need to match the keys we wish to use in our data-classes.

Note: There isn’t a great deal of work required to convert a KnockoutJS application from using traditional data-bindings over to unobstrusive bindings with custom binding providers. We simply pull our all of our data-bind attributes, replace them with data-class attributes and place our bindings in a binding object as per below:

var viewModel = new ViewModel(todos || []);
var bindings = {
        newTodo:  {
            value: viewModel.current,
            valueUpdate: 'afterkeydown',
            enterKey: viewModel.add
        },
        taskTooltip :  { visible: viewModel.showTooltip },
        checkAllContainer :  {visible: viewModel.todos().length },
        checkAll: {checked: viewModel.allCompleted },
        todos: {foreach: viewModel.todos },
        todoListItem: function() { return { css: { editing: this.editing } }; },
        todoListItemWrapper: function() { return { css: { done: this.done } }; },
        todoCheckBox: function() {return { checked: this.done }; },
        todoContent: function() { return { text: this.content, event: { dblclick: this.edit } };},
        todoDestroy: function() {return { click: viewModel.remove };},
        todoEdit: function() { return {
            value: this.content,
            valueUpdate: 'afterkeydown',
            enterKey: this.stopEditing,
            event: { blur: this.stopEditing } }; },
        todoCount: {visible: viewModel.remainingCount},
        remainingCount: { text: viewModel.remainingCount },
        remainingCountWord: function() { return { text: viewModel.getLabel(viewModel.remainingCount) };},
        todoClear: {visible: viewModel.completedCount},
        todoClearAll: {click: viewModel.removeCompleted},
        completedCount: { text: viewModel.completedCount },
        completedCountWord: function() { return { text: viewModel.getLabel(viewModel.completedCount) }; },
        todoInstructions: {visible: viewModel.todos().length}
    };
    ....

There are however two lines missing from the above snippet – we still need our getBindings function, which will loop through each of the keys in our data-class attributes and build up the resulting object from each of them. If we detect that the binding object is a function, we call it with our current data using the context this. Our complete custom binding provider would look as follows:

    // We can now create a bindingProvider that uses
    // something different than data-bind attributes
    ko.customBindingProvider = function(bindingObject) {
        this.bindingObject = bindingObject;
        //determine if an element has any bindings
        this.nodeHasBindings = function(node) {
            return node.getAttribute ? node.getAttribute("data-class") : false;
        };
      };
    // return the bindings given a node and the bindingContext
    this.getBindings = function(node, bindingContext) {
        var result = {};
        var classes = node.getAttribute("data-class");
        if (classes) {
            classes = classes.split(' ');
            //evaluate each class, build a single object to return
            for (var i = 0, j = classes.length; i < j; i++) {
               var bindingAccessor = this.bindingObject[classes[i]];
               if (bindingAccessor) {
                   var binding = typeof bindingAccessor == "function" ? bindingAccessor.call(bindingContext.$data) : bindingAccessor;
                   ko.utils.extend(result, binding);
               }
            }
        }
        return result;
    };
};

Thus, the final few lines of our bindings object can be defined as follows:

    // set ko's current bindingProvider equal to our new binding provider
    ko.bindingProvider.instance = new ko.customBindingProvider(bindings);
    // bind a new instance of our ViewModel to the page
    ko.applyBindings(viewModel);
})();

What we’re doing here is effectively defining constructor for our binding handler which accepts an object (bindings) which we use to lookup our bindings. We could then re-write the markup for our application View using data-classes as follows:

<div id="create-todo">
                <input id="new-todo" data-class="newTodo" placeholder="What needs to be done?" />
                <span class="ui-tooltip-top" data-class="taskTooltip" style="display: none;">Press Enter to save this task</span>
            </div>
            <div id="todos">
                <div data-class="checkAllContainer" >
                    <input id="check-all" class="check" type="checkbox" data-class="checkAll" />
                    <label for="check-all">Mark all as complete</label>
                </div>
                <ul id="todo-list" data-class="todos" >
                    <li data-class="todoListItem" >
                        <div class="todo" data-class="todoListItemWrapper" >
                            <div class="display">
                                <input class="check" type="checkbox" data-class="todoCheckBox" />
                                <div class="todo-content" data-class="todoContent" style="cursor: pointer;"></div>
                                <span class="todo-destroy" data-class="todoDestroy"></span>
                            </div>
                            <div class="edit">
                                <input class="todo-input" data-class="todoEdit"/>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>

Neil Kerkin has put together a complete TodoMVC demo app using the above, which can be accessed and played around with here.

Whilst it may look like quite a lot of work in the explanation above, now that you have a generic getBindings method written, it’s a lot more trivial to simply re-use it and use data-classes rather than strict data-bindings for writing your KnockoutJS applications instead. The net result is hopefully cleaner markup with your data bindings being shifted from the View to a bindings object instead.

MVC Vs. MVP Vs. MVVM

Both MVP and MVVM are derivatives of MVC. The key difference between it and it’s derivatives is the dependency each layer has on other layers as well as how tightly bound they are to each other.

In MVC, the View sits on top of our architecture with the controller laying below this. Models sit below the controller and so our Views know about our controllers and controllers know about Models. Here, our Views have direct access to Models. Exposing the complete Model to the View however may have security and performance costs, depending on the complexity of our application. MVVM attempts to avoid these issues.

In MVP, the role of the controller is replaced with a Presenter. Presenters sit at the same level as views, listening to events from both the View and model and mediating the actions between them. Unlike MVVM, there isn’t a mechanism for binding Views to ViewModels, so we instead rely on each View implementing an interface allowing the Presenter to interact with the View.

MVVM consequently allows us to create View-specific subsets of a Model which can contain state and logic information, avoiding the need to expose the entire Model to a View. Unlike MVP’s Presenter, a ViewModel is not required to reference a View. The View can bind to properties on the ViewModel which in turn expose data contained in Models to the View. As we’ve mentioned, the abstraction of the View means there is less logic required in the code behind it.

One of the downsides to this however is that a level of interpetation is needed between the ViewModel and the View and this can have performance costs. The complexity of this interpretation can also vary – it can be as simple as copying data or as complex as manipulating them to a form we would like the View to see. MVC doesn’t have this problem as the whole Model is readily available and such manipulation can be avoided.

Backbone.js Vs. KnockoutJS

Understanding the subtle differences between MVC, MVP and MVVM are important but developers ultimately will ask whether they should consider using KnockoutJS over Backbone based in what we’ve learned. The following notes may be of help here:

  • Both libraries are designed with different goals in mind and its often not as simple as just choosing MVC or MVVM

  • If data-binding and two-way communication are are your main concerns, KnockoutJS is definitely the way to go.Practically any attribute or value stored in DOM nodes can be mapped to JavaScript objects with this approach.

  • Backbone excels with its ease of integration with RESTful services, whilst KnockoutJS Models are simply JavaScript objects and code needed for updating the Model must be written by the developer.

  • KnockoutJS has a focus on automating UI bindings, which requires significantly more verbose custom code if attempting to do this with Backbone. This isnt a problem with Backbone itself par se as it puposefully attempts to stay out of the UI. Knockback does however attempt to assist with this problem.

  • With KnockoutJS, we can bind our own functions to ViewModel observables, which are executed anytime the observable changes. This allows us the same level of flexibility as can be found in Backbone

  • Backbone has a solid routing solution built-in, whilst KnockoutJS offers no routing options out of the box. One can however easily fill this behaviour in if needed using Ben Alman’s BBQ plugin or a standalone routing system like Miller Medeiros’s excellent Crossroads.

To conclude, I personally find KnockoutJS more suitable for smaller applications whilst Backbone’s feature set really shines when building anything non-trivial. That said, many developers have used both frameworks to write applications of varying complexity and I recommend trying out both at a smaller scale before making a decision on which might work best for your project.

References/Further Reading

29 Comments

  1. Pingback: In the News: 2012-04-11 | Klaus' Korner

  2. Pingback: Understanding MVVM – A Guide For JavaScript Developers | The Creative Web Project

  3. Pingback: Linkdump for April 11th | found drama

  4. awesome stuff as usual. really small thing though, you misspelled dependency in the first paragraph of the section, “MVC Vs. MVP Vs. MVVM”. Thanks for everything you do for the community!

  5. Thanks for delivering such a rich content on JS, learning by example on such quality code is definetly the way to go. Keep on teaching the world.

  6. if i create and set data-bind attribute for the required dom elements on dom ready, and then call ko.applyBindings is it bad practice?

  7. Really useful post summarising MVVM in a simplistic yet informative way. Has definitely inspired me to give both Backbone and Knockout a go!

  8. Shouldn’t “editing” attribute be part of ViewModel, if ViewModel is the one responsible for keeping track of presentational state?

    I always feel iffy having presentational attributes in Backbone models — “open” (for collapsible panels), “editing” (for editable elements), “selected” (for selectable lists), etc.

    Was surprised to see it being part of model in this example too.

    Relatedly, I think Presentation Model (http://martinfowler.com/eaaDev/PresentationModel.html) is supposed to solve this, but it always feels like too much unnecessary cruft to create a wrapper around model for only that purpose.

  9. awesome post as usual,
    i like this 2 libraries but in most cases Backbone.js is better fit, so my thought was why not combine them both (although its not exactly the mvvm pattern).

    so i added bindings, and bind the view to the model and then i got the good stuff of both of them.

    btw Ember.js its the best example for a library doing that.

  10. Great post!
    I’ve been plowing through your material the past few days and got to wonder about a slight difference in opinion regarding Backbone. I’m guessing the conclution you made in this post is what is most current, but I might as well ask anyways.

    Here you state that “I personally find KnockoutJS more suitable for smaller applications whilst Backbone’s feature set really shines when building anything non-trivial”. While reading some of your older material such as the “Tools for JQuery Application Architecture” slides and the print edition chart with the same name, you state that Backbone is “Excelent for a lightweight solution” and “Works best for SPAs”.

    I’m not trying to be a critic, I admire all the work you’ve done so far, I’m simply trying to make the best choice for an enterprise, large-scale application. I have no previous experience with either Backbone or KnockoutJS so what you write here might well be a large part of the deciding factor.

    Anywho, would greatly appreciate any response to my question. Keep up the great work.

    • Hello Patrik,

      No worries at all!. I was recently approached by another reader with a similar question. Because some of the older articles and charts on my site were put together back when Backbone.js was still quite young, there are slight changes in opinion that occurred over time as to just how well it could be suited for larger applications. Indeed, there have been quite a large number of non-trivial sites and applications built using it and I would recommend trying out both solutions just to see how well they fit the project you’re working on.

      With respect to Knockout.js, it’s also been used for non-trivial sites, but I would say that (for me personally) using it comes down to whether or not you’re a fan of data bindings. You may have noticed that I covered in my MVVM article how to get around bindings in your markup. Whilst this is possible, I think that if you’re going to take the effort to get around a big part of what makes Knockout different to other frameworks, you’re better off using something lightweight like Backbone (note lightweight here just means it’s small and flexible).

      I hope that helps!
      Addy

  11. Pingback: Weekly HTML5 Apps Developer Resources, April 25th 2012 ✩ Mozilla Hacks – the Web developer blog

  12. Pingback: MVVM in JavaScript « ClicData Code Bits

  13. Pingback: Architecting a MVC web application with Knockout « thewayofcode

  14. Pingback: 2012.06.02阅读分享 - 我行我思

  15. Would you agree today’s javascript apps are

    MVVM
    or
    MVP

    in the context of the screen being displayed.

    They still need a stub aka Router which knows how to connect to a remote resource. The remote resource would then have its own delegation model most probably a MVC front controller.

    MVVM / R and MVC.

    interested to know your thoughts Addy.

    • I would say the majority of them are predominantly MVP, although most frameworks label themselves MVC. Those that are MVC (the original/true form) or MVVM tend to be authored by developers who actively want to use harness specific aspects of those patterns and don’t mind the variations frameworks of today are actually using.

  16. Great post as usual Addy :)

    do you think using the looser data-binding approach will result in a better performance ?
    since we skipped parsing data-binding string attributes ?

    one more thing, I think in your `MVVM With Looser Data-Bindings` example there is an extra closing bracket `};` inside `ko.customBindingProvider` right after `this.nodeHasBindings`

  17. I would like to read more on your point:

    “You don’t want to end up in a situation where bindings are heavier than the objects being bound to.”

    Why?

  18. I have used mvvm in KnockoutJS, while we were programming for a college project which handles all machinery in a factory, mostly CNC. But when we tried integrating two machinery shutdown mode, we got stuck with couple of errors. I must have read this post then, so that it would have been helpful real-time.

  19. Pingback: Dynamic repeating field groups in ASP.Net MVC (with just a dash of Knockout.JS) « Roysvork

  20. Hmm it seems like your blog ate my first comment (it was super long) so I guess I’ll just
    sum it up what I submitted and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I’m still new to
    everything. Do you have any points for novice blog writers?

    I’d definitely appreciate it.

  21. Pingback: Quora

Leave a Reply

Required fields are marked *.