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?
To access the
relativeurlattribute of a Backbone model, you saym.get('relativeurl'); the attribute is not stored as a property of the model so this:will always yield
undefinedforthis.relativeurl. You should say:Demo: http://jsfiddle.net/ambiguous/VBQ5h/
You could also access the attribute directly through
this.attributesbut you should usually leaveattributesalone: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_propertyoro['some_property']. Backbone models deal primarily with attributes which are stored in the model’sattributesproperty and are accessed throughgetand modified throughset(and of coursefetch,unset, andclear). Backbone models don’t know anything about arbitrary object properties.