Giter Site home page Giter Site logo

dhruvaray / backbone-associations Goto Github PK

View Code? Open in Web Editor NEW
492.0 18.0 75.0 4.84 MB

Create object hierarchies with Backbone models; Respond to hierarchy changes using regular Backbone events.

Home Page: http://dhruvaray.github.io/backbone-associations/

License: MIT License

JavaScript 97.71% TeX 0.11% CSS 2.19%

backbone-associations's Introduction

Backbone-associations Build Status

Associations allows Backbone applications to model 1:1 & 1:N associations between application models and Collections. More importantly, applications can listen to any kind of change (change, add, remove, reset, sort, destroy) in this hierarchy using standard Backbone events and respond to them. (views can re-render for example). The implementation strives to be tiny (3.6KB), easy-to-understand, light-weight and fast.

For features, performance #s, API documentation, tutorials and recipes, please visit :

http://dhruvaray.github.io/backbone-associations/.

Who uses Backbone-Associations?

See #55

We encourage you to add your experiences to this list!

backbone-associations's People

Contributors

arirahikkala avatar avaly avatar bernii avatar bitdeli-chef avatar dak avatar dhruvaray avatar elliotf avatar freakenk avatar jackca avatar jdkanani avatar mradm avatar msteinert avatar ralfthewise avatar ronen avatar sdemjanenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

backbone-associations's Issues

Saving child of Model in Collection result in improper overwrite on return

I have a collection of models, each model has a one-to-one mapping with a child.

An editor is used to modify the child object and save it, upon success, the _byID property on the collection gets modified such that the child becomes the collection object, instead of remaining on as a child.

For instance - in pseudo code

var collection = Backbone.Collection.extend({
    model : Parent
})


Parent = {
    relations : [
            {
                type : Backbone.One,
                key : "child",
                relatedModel : Child
            }
        ]   

    Career : "",
    Address: "",
    child : null
}


Child = {
  FavoriteToy: "",
  Color: ""
}


/// Make test call to get parent:
collection.get(1); ///  returns the appropriate parent

function : updateAndSaveChild(){
    parent.get("child").set({ color : blue})

    parent.get("child").save({
        success : function(){

            ///  Make test call to get parent
            collection.get(1); ///  returns the CHILD object.
        }
    })
}

Upon inspection, the raw collection is in tact (collection.models), but the _byID object has been replaced.

I've stepped through and found this occurring in the Collection.OnModelEvent function:

 _onModelEvent: function(event, model, collection, options) {
      if ((event == 'add' || event == 'remove') && collection != this) return;
      if (event == 'destroy') {
        this.remove(model, options);
      }
      if (model && event === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        this._byId[model.id] = model;
      }
      this.trigger.apply(this, arguments);
    }

passing {silent : true} as an option fixes the problem.

Simple Store

Hi. Not sure if you consider this out of your scope, but I'd like to have the ability to reference a store Collection. One of the reasons I'm checking out backbone-associations is because BBRelational's store/caching got buggily aggresive. My simpler use case here, however, is for something like a store of Options based on the id attribute.

var InputClass = BB.Model.extend();

var InputCollection = new BB.Collection([{id: 'text', value: 'text box', validationOptions: ...}, {id: 'select', value: 'Select Dropdown', validationOptions: ....}], { model: InputClass});

var FieldClass = new BB.AssociatedModel({
    relations: [
    { type: Backbone.One, key: 'field', relatedModel: InputClass, store: InputCollection }
    ]
});

var first = new FieldClass({name: 'First Name', type: 'text'});
var job = new FieldClass({name: 'Job', type: 'select'});

Basically a pretty simple setup, but all possible relatedModels will be prepopulated in a collection.

On the instantiaton's call of setAttr (around line 130), it'd check do something like:

val ! instanceof AssociatedModel && store && store instanceof BB.Collection && _.isString(val) && store.get(val) && val = store.get(val);

it could even add back to the store afterwards if it wasn't originally found.

Object references seem to get broken after collection.set

Hi, we've been evaluating bb-associations for use in our webapp but think there's an issue with objects being recreated when setting via blobs of json. Ive seen issue #31 but think there's still a problem there. Here's a test case that I believe demonstrates the problem ;

    test("nested set shouldnt destroy references", function () {

        var Team = Backbone.Collection.extend({
                model:Employee
            }),
            json1 = [{
                    id:'e1',
                    fname: "John",
                    manager: {
                        id:'m1',
                        fname:'Mikeeee'
                    }
                }, {
                    id:'e2',
                    fname: "Edgar"
                }],
            json2 = [{
                    id:'e1',
                    fname: "John",
                    manager: {
                        id:'m1',
                        fname:'Mike' //<----- changed
                    }
                }, {
                    id:'e2',
                    fname: "Edgar"
                }];

        var team = new Team(json1);
        var employee1 = team.at(0);
        var manager1 = employee1.get('manager');

        team.set(json2);
        //re-resolving reference will get new value as expected
        equal(employee1.get('manager.fname'), 'Mike');
        //Fails: direct reference to manager object will return old value
        equal(manager1.get('fname'), 'Mike');

    });

To give a bit more context - We have a rich model/collection hierarchy thats; a) used to drive a number of nested Marionette CollectionViews/CompositeViews etc and b) can be periodically updated in part or whole by large blobs of json. So it's important that references aren't broken to avoid UI re-draws.

Any thoughts?
Cheers,
Greg

multiple reverse relation

You added recently a way to set a reverse relation with the "parents" key.

One of my model is the child of two different model types (each using a different key attribute)

How will "parents" work in this case?

Events stop bubbling after a fetch

Setting up a collection with listener:

var f = new FCollection();
f.on('add', function (e) { .. } );
f.fetch();
f.at(0).get('xxx').add({});

Leads to the event add:xxx being triggered on f. w00t.

However, after another f.fetch(), adding models no longer triggers an event on f. If a reset is forced with f.fetch({ reset: true }), the events bubble up to f again, but this resets the models within f, which doesn't work in my scenario (each of these models is hooked up in it's own view).

Is this working as intended? Am I doing something wrong?

The relation defintion within f && JSON from the server:

relations: [{
    type: Backbone.Many,
    key: 'xxx',
    relatedModel: 'TS.UserModel'
}]
[{
    "id": 468,
    "name": "I am so cool",
    "xxx": [{
        "id": 415,
        "email": "[email protected]"
    }]
}]

ps // Thanks for this awesome lib.

should expose version attribute

Backbone, jQuery, and many other popular libraries define a version attribute, so that the version of the library can be determined by introspection. This library should do the same, to make it easier to maintain and identify.

Difference in setting nested model and collection attribute ( with fetch for exemple )

I'm facing a problem when fetching model with nested attributes cause the nested model to loose reference (be overrided) :

The use case is the following :

Model A having a nested Model B as attribute "nested" ( A.get("nested") -> B )

A.fetch()
A.get("nested").on("any event", anycallback)
A.fetch()
-> nested have been overrided so the attached event is now attach to the old "zombie" model B.

This is easily explaided by the snippet in setAttr :

else if (relation.type === Backbone.One && relatedModel) {
    data = val instanceof AssociatedModel ? val : new relatedModel(val);
        attributes[relationKey] = data;
    }

But the strangest thing is that the behaviour in setting a collection is not the same : you are using a reset is the value is not a collection:

if (!this.attributes[relationKey]) {
    data = collectionType ? new collectionType() : this._createCollection(relatedModel);
    data.add(val, relationOptions);
    attributes[relationKey] = data;
} else {
        this.attributes[relationKey].reset(val, relationOptions);
    delete attributes[relationKey];
}

I understand that the behaviour is tricky because you need to handle the cases where the nested models are manually sets ( by A.set("nested", B) for exemple) and where the dev is expecting the nested model to be set as it is. But at least the setAttr behaviour should be the same for a nested model and a nested collection in the case the attribute is not a backbone model or collection ( array or object )

The fix is easy :

just replace

else if (relation.type === Backbone.One && relatedModel) {
    data = val instanceof AssociatedModel ? val : new relatedModel(val);
    attributes[relationKey] = data;
}

by

else if (relation.type === Backbone.One && relatedModel) {
    if (val instanceof BackboneModel) {
        data = val;
        attributes[relationKey] = data;
    } else {
        if (!this.attributes[relationKey]) {
            data = val instanceof AssociatedModel ? val : new relatedModel(val);
            attributes[relationKey] = data;
        } else {
            this.attributes[relationKey].set(val, relationOptions);
            delete attributes[relationKey];
        }
    }
}

Throws error with fetch

I am getting an error while calling fetch() on a model. the response json from server exactly matches the model definitions. i cant figure out what i am missing...

Versions:

Backbone: 0.9.2

Backbone-associations: 0.2.0

TypeError: this.attributes[relationKey].off is not a function this.attributes[relationKey].off("all");

//this is the code i am using..

var ProductVariation = Backbone.AssociatedModel.extend({
defaults: {
ImageUrl:'',
Desc:''
}
});

var Product = Backbone.AssociatedModel.extend({
relations: [{
type: Backbone.Many,
key: 'ProductVariations',
relatedModel: ProductVariation
}],
url: '/GetProductById',
defaults: {
CategoryId: 0,
ProductVariations: [],
Summary: ''
}
});
am i missing something? any help appreciated...

errors for required options

Hi,

I've just spent around 3 hours debugging because I habitually entered typeof instead of type in my relation config. I had to follow execution deep into the library's code to spot that.

If you specify in docs that something is required, and the required option is not provided, please be more strict about it and throw some informative errors. Otherwise people will get silent failures, which is a nasty scenario to debug. Thanks.

Incorrect logic when determining index of model in associated collection

The following logic appears to be wrong in the _bubbleEvent method (~line 189):

      return eventObject === (changedModel instanceof AssociatedModel
          || changedModel instanceof BackboneCollection)
          ? changedModel : (model.get(initialTokens) || model);

I will submit a pull request with what I believe is the correct logic and a unit test demonstrating the issue.

triggering change events for associated models with fetch()

I've a simplified model with three levels of 1-to-many relations: webapp, panel and master.
Using a server call (mocked in the example) I'm successfully able to load and instantiate the models.

The main view is instantiated before the fetch and associated with the main model (webapp). All other views are instantiated and associated in the parent views.

The example is here: https://gist.github.com/3974610

My problem is that the change events of the related models are not triggered. I'm sure I'm doing something wrong here but I'm unable to find my mistake.

Any help is appreciated.

Getting attribute "key" of an associated child collection

Is there is a simple way to retreive the attribute "key" of a child collection from a parent model? I have a view that gets fed a dynamic collection, that is a child of a model. I need to use the attribute key in a conditional - but not sure how to best access it directly from the child collection. I can get the parent model using childCollection.parents[0], but this doesn't give me the key. Thanks for your help!

Calling toJSON whilst _processPendingEvents is running returns undefined

Hi,

If the events that are being processed call toJSON then the call to toJSON fails because this.visited is true.

I assume the reuse of this variable name is not intentional. Changing this.visited to this.eventsVisited in _processPendingEvents fixes the issue and doesn't break any tests

Omi

AMD and self-referencing

I use backbone-associations in a AMD requirejs application, that's working fine with your recipe.

But i want to set a relation with the same model (friends from user).
How can I achieve this ?

In your example of model related to the same model, you set relatedModel as a string and not the class directly. But how can I do this in AMD ?

Who uses Backbone-Associations?

A compilation of projects which use Backbone-Associations. Please add your own project or product to this list. It would be wonderful and motivating to hear your story!

How important is it to have an explicit reverse relation support?

BB Associations supports reverse (inverse) relationships implicitly - via the parents property. Do users of BB Associations see a value in supporting explicit reverse relations - in the style of Backbone-relational?

Zoo = Backbone.RelationalModel.extend({
    relations: [{
        type: Backbone.HasMany,
        key: 'animals',
        relatedModel: 'Animal',     
        reverseRelation: {
            key: 'livesIn',
            includeInJSON: 'id'
        }
    }]
});
Animal = Backbone.RelationalModel.extend({
});

can also be simply modeled as

Zoo = Backbone.AssociatedModel.extend({
    relations: [{
        type: Backbone.Many,
        key: 'animals',
        relatedModel: 'Animal',     
    }]
});
Animal = Backbone.AssociatedModel.extend({
    relations: [{
        type: Backbone.One,
        key: 'livesIn',
        relatedModel: 'Zoo',        
    }]
});

Would be nice to see an example of what explicit reverse relation support could bring to the table.

EDIT : 19th July

Also, reverse relations like the one defined in BB-Relational can cause ambiguity and coupling between model definitions.

For example

Animal = Backbone.RelationalModel.extend({
});

Zoo = Backbone.RelationalModel.extend({
  relations: [{
        type: Backbone.HasMany,
        key: 'animals',
        relatedModel: 'Animal',     
        reverseRelation: {
            key: 'livesIn',
            includeInJSON: 'id'
        }
    }]
});


House = Backbone.RelationalModel.extend({
    relations: [{
        type: Backbone.HasMany,
        key: 'pets',
        relatedModel: 'Animal',     
        reverseRelation: {
            key: 'livesIn',
            includeInJSON: 'id'
        }
    }]
});

var cat = new Animal({name:"kitty", livesIn:{name:"my sweet home"}});

cat.get('livesIn') instanceof House //true


var lion = new Animal({name:"ferocious", livesIn:{name:"NY ZOO"}});
lion.get('livesIn') instanceof Zoo //false!
lion.get('livesIn') instanceof House //true!

Object has no method '_processPendingEvents' with PageableCollection

I am trying to use Backbone-Associations with Backbone-Pageable

My collections extends from PageableCollections instead Backbone.Collection (if I extend from Backbone.Collection dont give me this error).

Model = Backbone.AssociatedModel.extend({
    idAttribute: '_id',
...
Collection = PageableCollection.extend({
     model: Model
...

The problem arise when collection.fetch() gives me
Uncaught TypeError: Object [object Object] has no method '_processPendingEvents'

Any clue to fix this?

Fetch parent model and triggering a reset on child collections

I have a parent model, SearchResults, that has a 1-to-M relationship to a ProductsCollection and a 1-to-1 relationship to a SearchFacet model. The SearchFacet model is a parent of four 1-to-M collections, Categories, Brands, Vendors, Tags.

When I run a fetch on the SearchResults model, the results from the server are "set" on the child collections, but I need a way to treat them as a "reset". I need the server data from the fetch to completely overwrite the full set of parent and child models / collection.

Is this possilble? Or should I simply unset the parent SearchResults model before each new fetch?

Differences with Backbone-Relational

Just curious on all the known differences between backbone-associations and backbone-relational? I know that backbone-associations doesn't support reverse relations but I'm wondering what other functionality is different.

Would also be cool to see updated benchmarks since backbone-relational has had several big performance improvements recently.

Collection Change Events

I'm using Backbone Associations with some great success - thanks for the brillant extension. One question that has come up is how to listen for colleciton changes when the collection is nested into a parent Model? I have a model called Account, with a related subModel called Cart. Inside the Cart model is a collection of OrderItems on the Items attribute. I'm trying to bubble up events so that when a user changes the Quantity of an OrderItem, there is a change event on the Account.Cart.Items collection.

this.listenTo(RF.Models.Account,'change:Cart.Items[0].Quantity',function(){
    console.log('this works!');
});

this.listenTo(RF.Models.Account,'change:Cart.Items',function(){
    console.log('this doesn't!);
});

I'm trying to use BB Stickit to bind the Cart info to dom elements and have it auto-update when the OrderItems are changed, but it only refreshed when the Cart is changed directly (eg. a fetch to Account). I've tried bind to both the Cart and Cart.Items - the later comes through Stickit just fine as a collection.

bindings: {
    '#cart_btn_subtotal': {
        observe: ['Cart','Cart.Items'],
        onGet: function(values) {
            return values[0].get('ClientSubTotal');
        }
    },
    '#cart_btn_count': {
        observe: ['Cart','Cart.Items'],
        onGet: function(values) {
            return values[0].get('ItemCount');
        }
    }
}

self.stickit(RF.Models.Account);

Any ideas? Thanks for the help!

Question: Why are nested models always saved when parent is saved?

I have a hierarchy like this:

Project > Group > Task

First I create a Project, assign a Group to it, by getting the relation-object and calling add() on it. Then I assign some tasks to the group.

When i now call save() on the project, it will of course save the whole Project, including its nested models. But when I call save() on every single task, before i call save() on the project, it will still PUT the project including all groups and tasks, even though the tasks didn't change.

isNew() on the model reports 'false' and 'changed' is an empty object. So the model really didn't change. Why is it still being saved? Is this desired behavior? Or am I missing something?

Parent-chain behaviour issue

I am experiencing some issues with broken child->parents chain in some cases.

Here's a reduced example that shows the problem:

var Nested = Backbone.AssociatedModel.extend();

var Child = Backbone.AssociatedModel.extend({
    relations : [{
        type: Backbone.One,
        key : 'nested',
        relatedModel: Nested
    }]
});

var Root = Backbone.AssociatedModel.extend({
   relations : [{
       type: Backbone.One,
       key : 'child',
       relatedModel: Child
   }, {
       type: Backbone.One,
       key : 'nested',
       relatedModel: Nested
  }]
});

var root = new Root;
var child  = new Child;

// Add 'nested' to root model
root.set('nested', new Nested);
console.assert(root.get('nested').parents[0] === root, 'not ok');

// Add 'nested' to child model
child.set('nested', new Nested);
console.assert(child.get('nested').parents[0] === child, 'not ok');

// Add child to parent
root.set('child', child);
console.assert(root.get('nested').parents[0] === root, 'not ok'); // <= this will assert

The culprit seems to be this line:

https://github.com/dhruvaray/backbone-associations/blob/master/backbone-associations.js#L170

I can't really figure out what the intended purpose of removing the current model from the parent list of one of its attributes is:

original.parents = _.difference(original.parents, [this]); // Line 170

If I comment this out everything works as expected, but I am not sure this does not produce unwanted side-effects elsewhere.

Thanks!

Changed association does not reflect in #changedAttributes

Why is it that when I add an association, I cannot see the changed attributes?

p = new Project
>> Project {cid: "c21", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
p.changedAttributes()
>> false
p.get('users').add(u)
>> Backbone.Collection {length: 1, models: Array[1], _byId: Object, model: function, _proxyCallback: function…}
p.changedAttributes()
>> false

Support for Backbone 1.0 (bower config)

Hi,

Backbone Associations currently doesn't indicate support for Backbone 1.0. There shouldn't really be any changes that should affect this project (except for maybe the changes to model validation).

I'm using it right now together with Backbone 1.0, but it would be nice to get rid of the error messages from Bower.

Doesn't work with browserify

Backbone associations can not be used in a browserify stack as both the window and exports modules are defined as objects at runtime on the clientside. For this reason, the require('backbone') etc calls are not made and so instead it assigns Backbone and _ to exports._ and exports.Backbone, which are by definition, empty. Presumably that branch of the if logic should only fire when root == window and never root == exports as it does now in a browserify environment.

(typeof exports === "object") instead of (typeof window === "undefined") resolves the issue. Basically the key is to give priority to checking exports over window first.

One way I've seen which seems to cover all the bases is:

  // CommonJS
  if (typeof exports == "object") {
    var _ = require("underscore"),
    Backbone = require("backbone");
    exports = module.exports = Backbone;
  }
  // Browser
  else if (typeof _ !== "undefined" &&
    typeof Backbone !== "undefined") {
    _ = root._;
    Backbone = root.Backbone;
  }

reverse relation

how can i get reverse relation like one that's in backbone-relational?

Cannot read property '_bubbleEvent' of undefined

Hi,
I have been getting the following error when fetching new models with a Backbone.One relation.

Uncaught TypeError: Cannot read property '_bubbleEvent' of undefined
backbone-associations.js:161

I am on version 0.4.1.

I am not really sure what is causing this. How can I help to debug the problem further?

IE8 does not natively support [].indexOf, any reason not to use underscores implementation?

I wanted to make an app that's backwards-compatible with IE8, but I am getting fatal error loading up backbone-associations because on line 179 it use the native indexOf method on an array:

(updated.parents.indexOf(this) == -1) && updated.parents.push(this);

This method doesn't exist in IE8, so I was wondering if it would be possible to use underscore's indexOf implementation, which uses the native version if it exists. It seems that I am able to get backbone-associations to work in IE8 simply changing line 179 to this:

 (_.indexOf(updated.parents, this) == -1) && updated.parents.push(this);

Just wondering, is there a reason this wasn't done? Perhaps there are other more substantial issues with trying to support IE, but on the surface this seems like a worthwhile change.

P.S. thanks so much for this extension.

examples

Tried to run the example in the README file. I run into a few issues.

First, Employee must be specified globally (in the window namespace) otherwise eval(relatedModel) in line 144 fails.

The key 'manager' (mind the typo) in the defaults section of Employee must be set null. If it is set to {}, as in the example, javascript goes wild and results in 'too much recursion'

The statement:

project1.get('locations').on('reset', function() {
   ...
});

fails if 'locations' in Project is not set to [] in the defaults section. Maybe it should be set to [] by default

Backbone.AssociatedModel not populating

I came over from Backbone-relational, because I thought it was broken, but this also seems to not be working correctly.

I have a key in my model, 'jobs' and when I use model.get('jobs') it is coming in as undefined. Strange thing is that IT DOES have this when I use console.log(model.attributes). I can see it has a jobs array, but it doesn't seem to parse it correctly. I'm using coffeescript:

class SomeNamespace.Models.User extends Backbone.AssociatedModel

  relations: [
    type: Backbone.Many
    key: 'jobs'
    relatedModel:SomeNamespace.Models.Job
  ]

  urlRoot: '/users'

Do I also have to make a collection for this to work?

collectionType benefits ?

First thanks for this awesome lib !!!

My question is: since collectionType is optional, could you explain in a more detailed way when we should use it ? It may be a useful documentation update.

Comparison with DeepModel

Hello! Just stumbled upon this library, and saw lots of praise for it.

We originally started with Backbone.Nested but then it became incompatible with newer versions of Backbone.

We then switched to DeepModel and have been mostly happy despite a few quirks.

Just wondering if anyone could help to highlight any major differences between DeepModel and backbone-associations. I'm curious about ease-of-use, bugs, cpu/memory usage, etc.

Having this info in the README might be a good way to help newcomers to decide which lib is best for them.

Issue using Backbone.AssociatedModel with CoffeeScript 'extends' keyword

Tried to use this framework using the standard way of extending in CoffeeScript:

class MyAssociatedModel extends Backbone.AssociatedModel
...

When I started to use the new models in some Jasmine tests, I received all sorts of errors.

When I use the form:

MyAssociatedModel = Backbone.AssociatedModel.extend {
...
}

This form seems to work. Is there something happening the extend function that isn't getting called when using CoffeeScript class extension?

Include options in nested-change events?

Is there a reason why the options passed to set aren't passed as an argument to nested-change callbacks?

I just added , args[2]:

this.trigger.apply(this, ["nested-change", eventPath, args[1], args[2]]);

global 'change' doesn't work

it is important to note that you can't listen to associated model changes just by having
this.on('change', callback);
You need to listen to this.on('change:associatedModel', callback)

Fetch in nested models possible?

I create a model that has 2 nested models. The nested models fetch data from different applications.
Must parent model override / extend "fetch" to execute the nested "fetch" method ?

Nested relationships fail to serialize inside Backbone.Self toJSON

When you create a Backbone.Self relationship, and that model has its own associations, the toJSON fails to serialize the nested models.

Example:

var Brand = Backbone.AssociatedModel.extend({
  defaults: {
    name: null
  }
});

var Product = Backbone.AssociatedModel.extend({
  relations: [
    {
      type: Backbone.One,
      key: "brand",
      relatedModel: Brand
    },
    {
      type: Backbone.One,
      key: "alternate",
      relatedModel: Backbone.Self
    }
  ]
});

var banana = new Product({id:1, alternate:{id:2, alternate: null, name:"Peach", brand: {id: 1, name: "Dole"} }, name:"Banana", brand:{id:1, name: "Chiquita"} });

When you try to access alternate.brand.name in an underscore template it fails, as "brand" has not been serialized to an object.

I might be missing something - thanks in advance for the help!

generating models/collections with fetch()

Suppose there are three models; app, panel and master. app hasOne panel and panel hasMany masters. A server call with fetch returns

{
    name: 'application',
    panel: {
      name: 'main panel',
      masters: [{
        name: 'header'
      },{
        name: 'footer'
      }]
    }
 }

How can I create a app instance, a panel instance and two master instances?
In the test file I noticed it can be done with the 'company' test, but I can not get the third level (= masters) instanciated. Should I write a dedicated parse function?

undefined attributes

Hi,

I m trying to add some object to an attribute which has Backbone.Many association. But how the attribute is undefined I cant call for add. How can I solve this?

"parents" property not built after page reload.

Hi all,
are evaluating a migration from Relational to Associations. Our current setup uses git version 2a88c59.

What we see is that the parents property is populated but after reloading the page it is empty.

Is that the expected behaviour?

"change:'child_model'" event not firing

Hello. I'm using your great backbone-relations implementation in a project with a music player, which can play musical albums with tracks.

I have a Player model with a child album:

class App.Models.Player extends Backbone.AssociatedModel
  relations: [
    type: Backbone.One
    key: 'album'
    relatedModel:'App.Models.Album'
  ]

  defaults:
    album: null
    current_track: null
    pending: null

  ........

And in AlbumView I create a new player instance if no any, or update album attribute with a new album:

class App.Views.Albums.AlbumView extends Backbone.View
  events: {
    "click .cover": "load"
  }

  load: ->
    if App.PlayerView
      App.PlayerView.model.set "album", @model
      console.log "New album: #{App.PlayerView.model.get('album').get('title')}"
    else
      player = new App.Models.Player({album: @model})
      App.PlayerView = new App.Views.Player.PlayerView({model: player})
      $('#player_box').html(App.PlayerView.render().el)
      player.on "change:album", ->
        console.log "Album changed"
    .....

When a new album cover is clicked console shows a message with a new album title, but "change:album" event does not trigger. Strange, but when I change my code to player.on "change" it fires when the album is changed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.