2012-08-15 64 views
0

我很难过这个。我有一个简单的骨干关系模型:骨干关系改变事件没有发射?

window.Site = Backbone.RelationalModel.extend({ 
    idAttribute: "_id", 
    // These are the relations to the user model. 
    relations: [{ 
     type: Backbone.HasMany, 
     key: 'users', 
     relatedModel: 'window.User' 
     }], 

}); 

我的用户模型(这是关系到网站的模式)是这样的:

//Site User model 
    // ------------- 

    window.User = Backbone.RelationalModel.extend({ 
    }); 

用户模型有意保持愚蠢的,因为我还在原型。

我从服务器接收到滋润网站和用户的JSON看起来是这样的:

{ 
_id: foo, 
users: [ 
username: bar, 
password: fizz 
]} 

我很为难的是听众。这是对的SiteView(这使得我SiteCollection)事件是这样的:

initialize: function() { 

    //basic bindings 
    this.model.bind('change', this.setSave, this); 
    this.model.bind('destroy', this.remove, this); 

    // bindings to sub-models 
    this.model.bind('add:users', this.setDetailsView, this); 
    this.model.bind('remove:users', this.setSave, this); 
    this.model.bind('change:users', this.setSave, this); 

add:usersremove:users事件触发罚款,但change:users事件不会。在DetailsView,这使得我的用户模型,我也有一些简单的事件绑定:

initialize: function() { 
    this.model.bind('change', this.render, this); 
    this.model.bind('destroy', this.remove, this); 

但是,出于某种原因,该change:users事件中的SiteView不火,而change事件在DetailsView一样。

难道这是因为:

  • change事件上的用户模型两种不同的观点,势必两次?
  • 用户模式不是双向的吗?
+0

此外,结合更新':users'给出了相同的结果 – CamelBlues 2012-08-15 18:53:26

回答

2

对我来说,它看起来像更新:事件并不像你预期的那样工作。根据我的理解,只有在关键字(即相关模型)发生变化时才会触发,但如果您更改其属性,则不会触发。这意味着,只有当您从一个用户切换到另一个用户时,它才会触发,而不是如果您更改现有用户的属性。这是我对源代码行711的理解。 什么可能的工作是类似的规定:

this.model.get('users').each(function(user){ 
    user.bind(change,this.render,this); 
},this); 
+0

谢谢!这是行得通的,但我认为可以通过在我的模型上设置'reverseRelation'来预测'update'事件。仍试图找出如何做到这一点......但这是一个很好的解决方案! – CamelBlues 2012-08-15 21:42:44

+0

它的作品很棒,让我们知道,如果相反的做法 – schacki 2012-08-15 22:04:15

+1

工程就像一个魅力! 'reverseRelation'不起作用 – CamelBlues 2012-08-24 02:18:03

0

更好的解决方案:

this.model.bind('relational:change:users', this.setSave, this); 
+0

你从哪里得到这个'relational:'语法?我没有看到任何文档。 – 2015-10-27 21:38:41