Вопрос

Question about MVVM and data binding in Kendo Mobile:

  • account.js:

    define([], function () {
        return {
            userPhone: 111
        };
    });
    
  • index.html:

      <p>Phone: <span id="test-span" data-bind="html: userPhone"></span>.</p>
    
  • home-view.js:

    define(["kendo", "app/account"], function (kendo, account) {
    
    var viewModel = kendo.observable({
        userPhone: account.userPhone
    });
    
    return {
        show: function() {
           viewModel.set("userPhone", account.userPhone); // LINE A
    
           account.userPhone = "222"; // LINE B
    
        },    
        viewModel: viewModel
    }
    });
    
    1. Without LINE A and LINE B, #test-span displays (null)
    2. With only LINE A, #test-span displays "111"
    3. With only LINE B, #test-span displays (null)

I understand why #2 behaves the way it does. I just doesn't understand why #1 and #3 behave as they do. I thought the whole point of MVVM and data-bindings is that I could update account.userPhone and have it update views globally without having to do viewModel.set.

Assuming I have home-view2.js, home-view3.js, etc, how can I update all viewModels will changing just the account property?

Это было полезно?

Решение

Line B would work or not depending on the framework used, in this case KendoUI is not dirty-checking based. This means setting account.userName directly will not work, the updates need to be done by calling special setters in model classes such as in line A.

For example AngularJs is based on dirty checking, so line B would work if put on a controller or called inside $apply, and there is no need for code like line A.

The way angular dirty checking works is by taking a snapshot of a plain javascript object, and then at appropriate moments (on event callbacks, ajax callback and setTimeouts) take another another snapshot.

If the two snapshots differ, all the components observing account.userName are updated, for example DOM elements - and this is how angular bidirectional binding with plain javascript objects works.

Have a look at angular KendoUI for an Angular library based on the Kendo widgets.

If you are interested in dirty checking and how it works, have a look at this podcast by the Angular authors, and this answer from them, where a comparison with framework like Knockout or Backbone is made.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top