• Stars
    star
    135
  • Rank 269,297 (Top 6 %)
  • Language
    JavaScript
  • Created about 12 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Computed fields for Backbone.Model

Build Status Dependency Status devDependency Status

Backbone.ComputedFields

Inspired by Derik Bailey's Backbone.Computed, Backbone.ComputedFields aims the same goal, but polished for real project needs.

Quick start

Instantiated in initialize method,

initialize: function () {
    this.computedFields = new Backbone.ComputedFields(this);
},

ComputedField is declared as computed in model,

computed: {

}

All properties inside are treated as computed fields.

computed: {
    grossPrice: {
        get: function () {
            return 105;
        }
    }
}

computed can also be a function returning an object.

computed: function() {
    return {
        grossPrice: {
            get: function () {
                return 105;
            }
        }
    };
}

Each property that declares get or set method is treated as computed.

Get the value of computed property,

model.get('grossPrice');    // -> 105 is returned

Dependent fields

In case that computed field depends on some other models fields,

computed: {
    grossPrice: {
        depends: ['netPrice', 'vatRate'],
        get: function (fields) {
            return fields.netPrice * (1 + fields.vatRate / 100);
        }
    }
}

Add depends object into computed field object, as array of dependent fields. Dependent fields are injected into corresponding get method, by passing initialized fields object inside,

var Model = Backbone.Model.extend({
    defaults: {
        'netPrice': 0.0,
        'vatRate': 0.0
    },

    initialize: function () {
        this.computedFields = new Backbone.ComputedFields(this);
    },

    computed: {
        grossPrice: {
            depends: ['netPrice', 'vatRate'],
            get: function (fields) {
                return fields.netPrice * (1 + fields.vatRate / 100);
            }
        }
    }
});

model = new Model({ netPrice: 100, vatRate: 20});
model.get('grossPrice')     // -> 120 is returned

Setting computed values

Besides of get computed field might have set method as well.

computed: {
    grossPrice: {
        depends: ['netPrice', 'vatRate'],
        get: function (fields) {
            return fields.netPrice * (1 + fields.vatRate / 100);
        },
        set: function (value, fields) {
            fields.netPrice = value / (1 + fields.vatRate / 100);
        }
    }
}

set function receives the fields object, with same names of properties as model attributes. If set function changes the value of property, the change is propagated to model. Typically, you should change only one field in set method.

Model changes

In case of depended field is changed, computed field is automatically updated

model.set({vatRate: 5});
model.get('grossPrice');        // -> 105 is returned

// or

model.set({netPrice: 120});
model.get('grossPrice');        // -> 126 is returned

In case of calculated field is changed, dependent field in automatically updated

model.set({grossPrice: 105});
model.get('netPrice');          // -> 100 is returned

Model events

To make views works correctly, it important to keep correct events distribution.

In case of depended field is changed,

model.set({netPrice: 120});

After that call, several events are triggered - change:netPrice, as a reaction of grossPrice updated, change:grossPrice is triggered.

In case of computed field is changed,

model.set({grossPrice: 80});

After that call, several events are triggered - change:grossPrice, as a reaction of netPrice updated, change:netPrice is triggered.

Model validation

The same rules as for usual Backbone.js model attributes rules are applied for computed ones. If model contains validate() method and invalid is being set, the change would not propagate into model attributes, error event is triggered instead.

Say, we have such validation function,

validate: function (attrs) {

    var errors = [];
    if (!_.isNumber(attrs.netPrice) || attrs.netPrice < 0) {
        errors.push('netPrice is invalid');
    }

    if (!_.isNumber(attrs.grossPrice) || attrs.grossPrice < 0) {
        errors.push('grossPrice is invalid');
    }

    return errors.length > 0 ? errors : false;
}

And change computed field,

model.set({grossPrice: ''});

The model is will remain in valid state, { netPrice: 100, vatRate: 20, grossPrice: 120 }.

Dependency function

Computed field might have dependency not only on internal model attributes, but on external objects too. For instance, the product show price depends on currency selected by user in currency widget. Besides properties names, depends: [] can accept function, that is responsible to fire callback if change occurred.

computed: {
    grossPrice: {
        depends: ['netPrice', 'vatRate', function (callback) {
            this.external.on('change:value', callback);
        }],
        get: function (fields) {
            return this.external.get('value');
        }
    }
}

JSON payload

By default all computed fields are treated as part of JSON payload,

model.toJSON()          // -> { "netPrice": 100, "grossPrice": 120, "vatRate": 20 };

To disable that add toJSON: false in computed field declaration,

computed: {
    grossPrice: {
        depends: ['netPrice', 'vatRate'],
        get: function (fields) {
            return fields.netPrice * (1 + fields.vatRate / 100);
        },
        set: function (value, fields) {
            fields.netPrice = value / (1 + fields.vatRate / 100);
        },
        toJSON: false
    }
}

If you'd like to force the computed fields into the JSON payload even if the toJSON option is false, pass computedFields: true to the toJSON function:

model.toJSON({ computedFields: true })

More details

Up-to-date and complete documentation is located at /test/spec/backbone.computedfields.spec.js.

Legal Info (MIT License)

Copyright (c) 2012 Alexander Beletsky

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

backbone-express-spa

Backbone.js + Express.js single page application boilerplate
JavaScript
431
star
2

elmah-mvc

Painless integration of ELMAH into ASP.NET MVC application
C#
266
star
3

ng-notifications-bar

Angular.js component for stylish and flexible top bar notifications.
JavaScript
149
star
4

brick

My boilerplate project for Node.js / React.js development
JavaScript
71
star
5

github-commits-widget

Simple javascript widget to show recent github commits
JavaScript
41
star
6

foundstyles

Cool looking and ready to use themes based on Foundation framework
JavaScript
30
star
7

candidate

Simple and nice continuous delivery for .NET web applications.
JavaScript
23
star
8

machiatto

Behaviour driven test framework.
JavaScript
23
star
9

toml-js

TOML parser implementation (node.js + browser)
JavaScript
23
star
10

dokku-bower-install

Dokku pluging to install bower dependecies
Shell
21
star
11

tdd.demand

A Web Crawler that crawle some job looking sites, analyze them, store data
C#
19
star
12

trackyt.net

New task tracking/time management application
JavaScript
17
star
13

ddp-server-event

The implementation of DDP server based on EventEmitter.
JavaScript
15
star
14

react-restify-isomorphic

Isomorphic, react-based application.
JavaScript
13
star
15

wonka

Sweet blog engine with github powered backend for ASP.NET MVC applications.
C#
9
star
16

sparkling

Building Reactive API's with Express.js and MongoDB
JavaScript
9
star
17

todomvc-aura

TodoMVC based on Aura
JavaScript
9
star
18

aspnet.mobile

Mobile Web Application for ASP.NET portal fans
JavaScript
9
star
19

beerncode

Kyiv Beer'n'Code website
C#
9
star
20

react-notifications-bar

The port of ng-notifications-bar to React
JavaScript
6
star
21

react-grunt-es6

React + Grunt + ES6
JavaScript
6
star
22

react-gulp-es6

React + Gulp + ES6
JavaScript
6
star
23

github-fs

Convenient way of working with Git (Github) remote repository as file system
C#
5
star
24

backbone-clickdebounce

Debounce multiple clicks for Backbone.Views
JavaScript
5
star
25

themailer

Demo application I've created for my conference talk
JavaScript
5
star
26

rest.mvc.example

Example of REST service by ASP.net MVC2 framework (for blog)
JavaScript
5
star
27

node-dev-server

Ideal for local single page applications development
JavaScript
3
star
28

10k

My humble attempt to participate 10K Appart competetion
JavaScript
3
star
29

freeze

Easy way of making a snapshot of dynamic web site.
JavaScript
3
star
30

js-training

js-training
JavaScript
2
star
31

certificates

My archivements on online courses and other official stuff
2
star
32

benchmark-js

Very simple, javascript Date() dependable, console based benchmarking.
JavaScript
2
star
33

tdd-starter

Ready to use sandbox for TDD with JS
JavaScript
2
star
34

copter

Front-end apps deployment
1
star
35

alexbeletsky.github.io

My personal page and development blog
HTML
1
star
36

canteen

Node.js chat application with real time collaboration
JavaScript
1
star
37

ml-python

Materials created during studying Python Machine Learning book.
Jupyter Notebook
1
star
38

next-error

Express.js module that would which eliminates if / return for error handling.
JavaScript
1
star
39

numa-app

JavaScript
1
star
40

docker-deploy

Deploy tool for remote docker server
Shell
1
star
41

gameoflife

The Game of Life
JavaScript
1
star
42

backbone-aspnetmvc-spa

Backbone.js + ASP.NET MVC (Web API) single page application boilerplate
JavaScript
1
star