开发者

Backbone.js source read-through

开发者 https://www.devze.com 2023-04-10 12:34 出处:网络
I\'m reading through the Backbone.js source and am somewhat confused by these lines (L230-238, v0.5.3)

I'm reading through the Backbone.js source and am somewhat confused by these lines (L230-238, v0.5.3)

unset : function(attr, options) {
  if (!(attr in this.attributes)) return this;
  options || (options = {});
  var value = this.attributes[attr]; // ?: value appears to be unused (?)

  // Run validation.
  var validObj = {};
  validObj[attr] = void 0; //void 0 is equivalent to undefined
  if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;

Am I crazy or does the last line run a validation against a hash object with a single undefined attribute?

It seems like the validation is intended to run on an instance of the Model object with the attribu开发者_开发问答te-to-be-unset removed.

Current source on github with lines highlighted


you're correct in your assessment of what it does, but that's the intended functionality.

when you call unset, you can only tell it to unset one attribute at a time: model.unset("myAttr")

when unsetting, validation is called to make sure the model will be put into a valid state. if the attribute being set to undefined will cause the model to be invalid, the unset fails. if it is valid for the attribute to be undefined, the attribute is removed from the model.

the reason it passes a "hash object with a single undefined attribute" is that all objects in javascript as "hash objects" - key value pairs, or associative arrays. it doesn't matter how you get an object, it is an associative array.

an object with one empty attribute named after the model's attribute that is being unset, is created in lines 236-237. this is so that monkeying with the object passed into the validate method won't change the state of the model itself.

hope that helps explain things.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号