Backbone.NestedModel
Issue listening for collection of NestedModels Change event
by mreis1
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<textarea id="my_item" hidden>
<span class="title"><%= name %></span>
<ul>
<% if (!_.isUndefined(address)) { _.each(address,function(item){ %>
<li> <%= item.street %>, <%= item.door %> </li>
<% })} %>
</ul>
</textarea>
<h1>Placeholder</h1>
<div class="placeholder"></div>
<a href="#" id="change_name">Change Mary Jane Name to Hellboy</a><br/>
<br/>
<a href="#" id="change_address">Change Capitan America street name from it's second address! <b>AND</b> also change "signle Person" street name </a>
CSS
.title{
color:red;
text-transform:uppercase;
}
JavaScript
/**
* Backbone-Nested 2.0.0 - An extension of Backbone.js that keeps track of nested attributes
*
* http://afeld.github.com/backbone-nested/
*
* Copyright (c) 2011-2012 Aidan Feldman
* MIT Licensed (LICENSE)
*/
(function($, _, Backbone) {
'use strict';
var _delayedTriggers = [],
nestedChanges;
Backbone.NestedModel = Backbone.Model.extend({
get: function(attrStrOrPath){
var attrPath = Backbone.NestedModel.attrPath(attrStrOrPath),
result;
Backbone.NestedModel.walkPath(this.attributes, attrPath, function(val, path){
var attr = _.last(path);
if (path.length === attrPath.length){
// attribute found
result = val[attr];
}
});
return result;
},
has: function(attr){
// for some reason this is not how Backbone.Model is implemented - it accesses the attributes object directly
var result = this.get(attr);
return !(result === null || _.isUndefined(result));
},
set: function(key, value, opts){
var newAttrs = Backbone.NestedModel.deepClone(this.attributes),
attrPath,
unsetObj,
validated;
if (_.isString(key)){
// Backbone 0.9.0+ syntax: `model.set(key, val)` - convert the key to an attribute path
attrPath = Backbone.NestedModel.attrPath(key);
} else if (_.isArray(key)){
// attribute path
attrPath = key;
}
if (attrPath){
opts = opts || {};
this._setAttr(newAttrs, attrPath, value, opts);
} else { // it's an Object
opts = value || {};
var attrs = key;
for (var _attrStr in attrs) {
if (attrs.hasOwnProperty(_attrStr)) {
this._setAttr(newAttrs,
Backbone.NestedModel.attrPath(_attrStr),
opts.unset ? void 0 : attrs[_attrStr],
opts);
}
}
}
nestedChanges =...