• Stars
    star
    444
  • Rank 97,862 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 13 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

A plugin to make Backbone.js keep track of nested attributes - looking for maintainers! https://github.com/afeld/backbone-nested/issues/157

Backbone-Nested Build Status

A plugin to make Backbone.js keep track of nested attributes. Download the latest version and see the changelog/history/release notes on the Releases page. Supports Backbone 0.9.x and 1.x.

The Need

Suppose you have a Backbone Model with nested attributes, perhaps to remain consistent with your document-oriented database. Updating the nested attribute won't cause the model's "change" event to fire, which is confusing.

var user = new Backbone.Model({
  name: {
    first: 'Aidan',
    last: 'Feldman'
  }
});

user.bind('change', function(){
  // this is never reached!
});

user.get('name').first = 'Bob';
user.save();

Wouldn't it be awesome if you could do this?

user.bind('change:name.first', function(){ ... });

Installation

Bower

Recommended.

  1. Install the latest version:

    bower install backbone backbone-nested-model jquery underscore --save
  2. Add backbone-nested.js to your HTML <head>:

    <!-- must loaded in this order -->
    <script type="text/javascript" src="/bower_components/jquery/jquery.js"></script>
    <script type="text/javascript" src="/bower_components/underscore/underscore.js"></script>
    <script type="text/javascript" src="/bower_components/backbone/backbone.js"></script>
    <script type="text/javascript" src="/bower_components/backbone-nested-model/backbone-nested.js"></script>

Manual

Download the latest release and the dependencies listed above, then include with script tags in your HTML.

Usage

  1. Change your models to extend from Backbone.NestedModel, e.g.

    var Person = Backbone.Model.extend({ ... });
    
    // becomes
    
    var Person = Backbone.NestedModel.extend({ ... });
  2. Change your getters and setters to not access nested attributes directly, e.g.

    user.get('name').first = 'Bob';
    
    // becomes
    
    user.set({'name.first': 'Bob'});

Best of all, Backbone.NestedModel is designed to be a backwards-compatible, drop-in replacement of Backbone.Model, so the switch can be made painlessly.

Nested Attributes

get() and set() will work as before, but nested attributes should be accessed using the Backbone-Nested string syntax:

1-1

// dot syntax
user.set({
  'name.first': 'Bob',
  'name.middle.initial': 'H'
});
user.get('name.first') // returns 'Bob'
user.get('name.middle.initial') // returns 'H'

// object syntax
user.set({
  'name': {
    first: 'Barack',
    last: 'Obama'
  }
});

1-N

// object syntax
user.set({
  'addresses': [
    {city: 'Brooklyn', state: 'NY'},
    {city: 'Oak Park', state: 'IL'}
  ]
});
user.get('addresses[0].state') // returns 'NY'

// square bracket syntax
user.set({
  'addresses[1].state': 'MI'
});

Events

"change"

"change" events can be bound to nested attributes in the same way, and changing nested attributes will fire up the chain:

// all of these will fire when 'name.middle.initial' is set or changed
user.bind('change', function(model, newVal){ ... });
user.bind('change:name', function(model, newName){ ... });
user.bind('change:name.middle', function(model, newMiddleName){ ... });
user.bind('change:name.middle.initial', function(model, newInitial){ ... });

// all of these will fire when the first address is added or changed
user.bind('change', function(model, newVal){ ... });
user.bind('change:addresses', function(model, addrs){ ... });
user.bind('change:addresses[0]', function(model, newAddr){ ... });
user.bind('change:addresses[0].city', function(model, newCity){ ... });

"add" and "remove"

Additionally, nested arrays fire "add" and "remove" events:

user.bind('add:addresses', function(model, newAddr){ ... });
user.bind('remove:addresses', function(model, oldAddr){ ... });

Special Methods

add()

Acts like set(), but appends the item to the nested array. For example:

user.get('addresses').length; //=> 2
user.add('addresses', {
  city: 'Seattle',
  state: 'WA'
});
user.get('addresses').length; //=> 3

remove()

Acts like unset(), but if the unset item is an element in a nested array, the array will be compacted. For example:

user.get('addresses').length; //=> 2
user.remove('addresses[0]');
user.get('addresses').length; //=> 1

See also

Note, this plugin does not handle non-embedded relations (a.k.a. relations), which keeps it relatively simple. If you support for more complex relationships between models, see the Backbone plugin wiki page. There is also an open discussion about merging this project with backbone-deep-model.

Contributing

Pull requests are more than welcome - please add tests, which can be run by opening test/index.html. They can also be run from the command-line (requires PhantomJS):

$ npm install
$ grunt

See also: live tests for latest release.

More Repositories

1

emoji-css

An easy way to include emoji in your HTML
JavaScript
892
star
2

mustachio

automatic mustachifying of any image
Ruby
344
star
3

jsonp

DEPRECATED - A proxy to help with cross-domain requests
JavaScript
302
star
4

rails_interview_questions

A list of some baseline Rails interview questions
298
star
5

magickly

image manipulation as a (plugin-able) service
Ruby
179
star
6

bootstrap-toc

An automatic table of contents generator, using Bootstrap 3 or 4
JavaScript
157
star
7

git-plugins

a collection of custom git commands
Shell
61
star
8

api.afeld.me

nerdiest homepage ever
Ruby
51
star
9

tricle

easy metrics reporting via email
Ruby
36
star
10

jeditable-rails

a gem to add in-place-editable fields to your Rails project
Ruby
35
star
11

python-public-policy

Python for Public Policy course
Jupyter Notebook
25
star
12

github_non_coding

a list of non-coding use cases of GitHub
Ruby
23
star
13

html_pipeline_rails

rendering views via HTML::Pipeline in Rails
Ruby
20
star
14

dotfiles

my dotfiles
Shell
17
star
15

github-find

Chrome extension for searching within a Github repo.
JavaScript
16
star
16

stringer

a project with Alex Chen and Tyler Williams for doing string drawing and plucking in Processing using the Kinect
Processing
15
star
17

jsonpanel

pretty JSON viewer jQuery plugin
CSS
12
star
18

git-setup

easy Git setup
Shell
12
star
19

teaching

a collection of materials/resources for teaching technology
10
star
20

3d-controller

demos of using a phone as a gestural interface
JavaScript
10
star
21

face_detect

a Ruby gem for face detection
Ruby
9
star
22

tfmv

proof of concept: a tool to help refactoring Terraform resources
Go
9
star
23

bike-report

messing with NYC CitiBike historical data
Ruby
8
star
24

sshkit-interactive

WIP: execute interactive commands on your servers via SSHKit
Ruby
7
star
25

mustachio-js

automatic mustachifying of any image
JavaScript
6
star
26

gh_collab

slides for "How GitHub Does Collaboration" talk
JavaScript
5
star
27

github_invite

app to enable GitHub users to easily add others to their organization teams
Ruby
5
star
28

sparkle

API for generating sparklines
Ruby
4
star
29

facial

WORK IN PROGRESS - Simple library for face detection using OpenCV
Ruby
4
star
30

spaa

Single-Page App Architecture talk
CSS
4
star
31

refactor

a command line tool to help refactor your code
Ruby
3
star
32

delivery

Continuous Delivery workshop materials
HCL
3
star
33

pose

experimenting with real-time pose detection and speech recognition for dance performance
TypeScript
3
star
34

hubot-twitter-config

WIP: configuration module for using Twitter via Hubot
CoffeeScript
3
star
35

repo-eyes

scripts to keep watch over your repositories
Ruby
2
star
36

careless

LESS rendering as a service
JavaScript
2
star
37

faacelift

JavaScript
2
star
38

tech-foundations

Columbia SPS Operations Management in IT course
JavaScript
2
star
39

compare_by

a better version of Ruby's Comparable
Ruby
2
star
40

test_to_learn

a talk about learning to code via testing
JavaScript
2
star
41

personal-security

Digital Security and Privacy for Normal People - a guide
HTML
2
star
42

practical_tdd

2
star
43

node-face

Face.com API wrapper for NodeJS
JavaScript
2
star
44

tdd_js

talk: Test-Drive Your JavaScript
JavaScript
2
star
45

data-cleaning

Data Cleaning Techniques workshop materials
Jupyter Notebook
2
star
46

filter_feeder

JavaScript
2
star
47

jekyll-git

a Jekyll plugin for retrieving data from Git
Ruby
2
star
48

geo_formatter

A JS wrapper for easier-to-work-with Google Geocoder results.
JavaScript
2
star
49

jquery-clearinput

Clears the instructions from an HTML form input on focus, replacing the text if nothing is entered.
JavaScript
2
star
50

SWICS-Fix

a little Python script to clean up some solar wind data
Python
1
star
51

flyloft

a jobs site for performing artists (a work in progress)
Ruby
1
star
52

multipass-examples

Examples on how to use Assistly's Multipass SSO
PHP
1
star
53

wedding

wedding website
HTML
1
star
54

markdown_proofer

Markdown validator gem
Ruby
1
star
55

photo-frame

[WORK IN PROGRESS] photo frame that automatically pulls from Facebook
TypeScript
1
star
56

arduino_low_battery

low battery indicator for Arduino
Arduino
1
star
57

tangle

a web page scanner to find broken links
Go
1
star
58

repowatch

JavaScript
1
star
59

threepenny

Ruby
1
star
60

ellipsis-test

test suite of plugins for handling multiline-text-overflow
1
star
61

hubot-trollbot

a hubot script that annoys your coworkers
CoffeeScript
1
star
62

paypal_form

A Radiant extension for a dynamic Paypal submission form.
Ruby
1
star
63

fontsmash

Ruby
1
star
64

temp

temperature sensor to prove my jerk of a landlord was breaking the law
Arduino
1
star
65

graffiti.js

Java
1
star
66

config_settings

a code test I did for a job application: creating a model which stores configuration settings
Ruby
1
star
67

mongo_ruby_workshop

Workshop for getting started using MongoDB with Ruby
Ruby
1
star
68

knowpickle

A site for learning things
Ruby
1
star
69

govern

automatic governance for your projects
Ruby
1
star
70

web_dev_basics

Web development workshop
PHP
1
star
71

rails-bottom-up

teaching Rails from the Bottom Up
Ruby
1
star
72

dotjunkd

my junk drawer
1
star
73

code_cruise

An app for discovering learning paths: given a set of knowledge and a goal, a self-motivated learner can find all the topics between them and that destination.
Ruby
1
star