javascriptcanjsdonejs

Calculated value not being updated correctly using donejs


I have standard donejs project with a component and a model both created using the default generators like this:

donejs add component storyBoard story-board
donejs add supermodel story

I left a sample project here: https://github.com/riescorp/donejs-promise-iterate

If you run this example using donejs develop and go to http://localhost:8080 you'll see something like this:

image

The problem is that whenever you change a value of the number of pages (input boxes) for any story, the sum won't update its value. I tried almost everything, from promises to already-resolved-promises but nothing seems to do the trick.

Somehow it seems that when any of those values change, there is no update trigger at all. I also tried setting the results as a List (can.List) but with no luck.


Solution

  • The problem seems to be that elem.pages should be elem.attr("pages").

    Here's a version of the code that works for me:

    export const ViewModel = Map.extend({
      define: {
        storyPromise: {
          get: function() {
            return Story.getList({});
          }
        },
        stories: {
          get: function(last, resolve) {
            this.attr("storyPromise").then(resolve);
          }
        },
        sum2: {
          get: function() {
            var total = 0;
            if (this.attr('stories') !== undefined) {
              this.attr('stories').each(function(elem) {
                total += parseInt( elem.attr("pages") );
              });
            }
            return total;
          }
        }
      }
    });
    

    You have to use .attr, otherwise, sum2 doesn't know when the pages property changes.