npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

backbone-computedfields

v0.0.12

Published

Computed fields for Backbone models

Downloads

539

Readme

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.