0

I have already define a model use backbone:

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);
        }
    });

Then I want invoke this method

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

but just I comment above,even I already invoke the set method ,the "relativeurl" result is still undefined!

What's wrong with my code?How can I solve this problem?

hh54188
  • 14,887
  • 32
  • 113
  • 184

1 Answers1

2

To access the relativeurl attribute of a Backbone model, you say m.get('relativeurl'); the attribute is not stored as a property of the model so this:

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

will always yield undefined for this.relativeurl. You should say:

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

Demo: http://jsfiddle.net/ambiguous/VBQ5h/

You could also access the attribute directly through this.attributes but you should usually leave attributes alone:

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

Demo: http://jsfiddle.net/ambiguous/y3Q6b/

Your real problem is probably confusion between object properties and Backbone attributes. Properties are fields of the object and are accessed as o.some_property or o['some_property']. Backbone models deal primarily with attributes which are stored in the model's attributes property and are accessed through get and modified through set (and of course fetch, unset, and clear). Backbone models don't know anything about arbitrary object properties.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Might be worth mentioning that Backbone's get/set doesn't get/set "properties" on a model object - it gets/stores "attributes" in a model object. I know it's silly and almost nit-picky, but properties always seem to be "object.someProperty", and backbone's documentation refers to them as a getter/setter for "attributes". – Stephen May 24 '12 at 04:01
  • @Stephen: There's nothing wrong with being picky about terminology. Is the updated version better? (I'm not being snarky, I really do care about clarity :) – mu is too short May 24 '12 at 04:09