Backbone.js:更改不会在model.change()上触发 [英] Backbone.js : change not firing on model.change()

查看:109
本文介绍了Backbone.js:更改不会在model.change()上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Backbone.js = /

I'm facing a "change event not firing" issue on Backbone.js =/

面临着一个改变事件不触发问题在这里我的用户模型视图:

Here my view of User model :

    window.UserView = Backbone.View.extend({

        ...

        initialize: function()
        {
            this.model.on('destroy', this.remove, this);

            this.model.on('change', function()
            {
               console.log('foo');
            });
        },

        render: function(selected)
        {
            var view = this.template(this.model.toJSON());

            $(this.el).html(view);

            return this;
        },

        transfer: function(e)
        {                
            var cas = listofcas;

            var transferTo = Users.getByCid('c1');
            var transferToCas = transferTo.get('cas');

            this.model.set('cas', cas);
            console.log('current model');
            console.log(this.model);

            //this.model.change();
            this.model.trigger("change:cas");
            console.log('trigger change');

            transferTo.set('cas', transferToCas);
            console.log('transferto model');
            console.log(transferTo);

            //transferTo.change();
            transferTo.trigger("change:cas");
            console.log('trigger change');

        }

    });

这里,用户模型:

window.User = Backbone.Model.extend({

        urlRoot: $('#pilote-manager-app').attr('data-src'),

        initialize: function()
        {
            this.set('rand', 1);
            this.set('specialite', this.get('sfGuardUser').specialite);
            this.set('name', this.get('sfGuardUser').first_name + ' ' + this.get('sfGuardUser').last_name);
            this.set('userid', this.get('sfGuardUser').id);
            this.set('avatarsrc', this.get('sfGuardUser').avatarsrc);
            this.set('cas', new Array());

            if (undefined != this.get('sfGuardUser').SignalisationBouclePorteur) {

                var cas = new Array();

                _.each(this.get('sfGuardUser').SignalisationBouclePorteur, function(value)
                {
                    cas.push(value.Signalisation);
                });

                this.set('cas', cas);

            }
        }
    });

在用户模型中,存在cas属性,它是一组对象。

In User model, there is "cas" attribute, which is an array of objects.

我读过其他主题,如果属性不是值,则更改事件不会在model.set上触发。

I read in others topics that change events are not fire on model.set if attributes are not a value.

所以,我试图用model.change()方法直接触发change事件。
但是,我没有foo登录到我的控制台...

So, I try to trigger directly the change event with model.change() method. But, I have no "foo" log in my console ...

推荐答案

我很新骨干,我也有同样的问题。

I'm pretty new to backbone and I was having this same problem.

在做了一些研究后,我发现了一些帖子,为什么会发生这样的事,开始有意义:

After doing some research, I found a few posts that shed a little bit more light on why this was happening, and eventually things started to make sense:

问题1

问题2

核心原因与引用平等与set / member相等的概念有关。看来在很大程度上,参考平等是骨干用来弄清属性何时改变的主要技术之一。

The core reason has to do with the notion of reference equality versus set/member equality. It appears that to a large extent, reference equality is one of the primary techniques backbone uses to figure out when an attribute has changed.

我发现如果我使用技术生成一个新的参考,如Array.slice()或_.clone(),更改事件被识别。

I find that if I use techniques that generate a new reference like Array.slice() or _.clone(), the change event is recognized.

所以例如下面的代码不会触发事件因为我改变了相同的数组引用:

So for example, the following code does not trigger the event because I'm altering the same array reference:

this.collection.each(function (caseFileModel) {
    var labelArray = caseFileModel.get("labels");
    labelArray.push({ Key: 1, DisplayValue: messageData });
    caseFileModel.set({ "labels": labelArray });
});

虽然此代码确实触发事件:

While this code does trigger the event:

this.collection.each(function (caseFileModel) {
    var labelArray = _.clone(caseFileModel.get("labels")); // The clone() call ensures we get a new array reference - a requirement for the change event
    labelArray.push({ Key: 1, DisplayValue: messageData });
    caseFileModel.set({ "labels": labelArray });
});

注意:根据 Underscore API ,_.clone()通过引用复制某些嵌套项目。根/父对象被克隆,所以它可以在骨干网上正常工作。也就是说,如果您的数组非常简单,并且没有嵌套结构,例如[1,2,3]。

NOTE: According to the Underscore API, _.clone() copies certain nested items by reference. The root/parent object is cloned though, so it will work fine for backbone. That is, if your array is very simple and does not have nested structures e.g. [1, 2, 3].

虽然我上面的改进代码触发了更改事件,但以下不是因为我的数组包含嵌套对象:

While my improved code above triggered the change event, the following did not because my array contained nested objects:

var labelArray = _.clone(this.model.get("labels"));
_.each(labelArray, function (label) {
    label.isSelected = (_.isEqual(label, selectedLabel));
});
this.model.set({ "labels": labelArray });

现在为什么这么重要?调试后非常仔细,我注意到,在我的迭代器中,我引用了相同的对象参考骨干存储。换句话说,我无意中进入了我的模型的内脏,翻了一下。当我打电话给setLabels()时,骨干网正确地认识到没有改变,因为它已经知道了我翻了一下。

Now why does this matter? After debugging very carefully, I noticed that in my iterator I was referencing the same object reference backbone was storing. In other words, I had inadvertently reached into the innards of my model and flipped a bit. When I called setLabels(), backbone correctly recognized that nothing changed because it already knew I flipped that bit.

人们似乎总是说,javascript中的深层复制操作是一个真正的痛苦 - 没有内置的。所以我做到这一点对我来说很好 - 一般适用性可能会有所不同:

After looking around some more, people seem to generally say that deep copy operations in javascript are a real pain - nothing built-in to do it. So I did this, which worked fine for me - general applicability may vary:

var labelArray = JSON.parse(JSON.stringify(this.model.get("labels")));
_.each(labelArray, function (label) {
    label.isSelected = (_.isEqual(label, selectedLabel));
});
this.model.set({ "labels": labelArray });

这篇关于Backbone.js:更改不会在model.change()上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆