0

我已经定义了一个模型使用主干:

window.ResourceModel = Backbone.Model.extend({

        default:{
            'relativeurl':'unknow',
            'type': "unkonw"
        },

        initialize: function(){

            this.bind("change:relativeurl", function () {
                console.log('change!',this.relativeurl);
            });

            this.bind("change:type", function () {

            });
        },

        setRelativeURL: function (url) {
             console.log('pass in',url);//this have value
             this.set({"relativeurl": url});//this's value is undefined!
        },

        delResource: function () {
            console.log("this.url",this.relativeurl);
            resourceMasterView.delResourceItem(this.url);
        }
    });

然后我想调用这个方法

window.resourceModel = new ResourceModel();
resourceModel.setRelativeURL(url);
resourceModel.setType(type);

但只是我在上面评论,即使我已经调用了 set 方法,“relativeurl”结果仍然是未定义的!

我的代码有什么问题?我该如何解决这个问题?

4

1 回答 1

2

要访问relativeurlBackbone 模型的属性,你说m.get('relativeurl');该属性未存储为模型的属性,因此:

console.log('change!', this.relativeurl);

将始终undefinedthis.relativeurl. 你应该说:

console.log('change!', this.get('relativeurl'));

演示:http: //jsfiddle.net/ambiguous/VBQ5h/

您也可以直接通过以下方式访问该属性,this.attributes但通常应该不理会attributes

console.log('change!', this.attributes.relativeurl);

演示:http: //jsfiddle.net/ambiguous/y3Q6b/

您真正的问题可能是对象属性Backbone 属性之间的混淆。属性是对象的字段,可以作为o.some_property或访问o['some_property']。主干模型主要处理存储在模型属性中的属性,并通过(当然还有、和)attributes访问get和修改。骨干模型对任意对象属性一无所知。setfetchunsetclear

于 2012-05-24T03:42:36.383 回答