Models

AJAX Abstraction for a Single Resource

set

The set() method can be used to set attributes on the model outside the constructor.

Default Implementation

The default implementation looks like this:

set: function(key, val, options) {
  if (key == null) {
    return this
  };

  let attrs;
  if (typeof key === 'object') {
    attrs = key;
    options = val;
  } else {
    (attrs = {})[key] = val;
  }

  options || (options = {});

  if (!this._validate(attrs, options)) return false;

  const current = this.attributes;

  for (const attr in attrs) {
    val = attrs[attr];
    current[attr] = val;
  }

  if (this.idAttribute in attrs) {
    this.id = this.get(this.idAttribute)
  };

  return this;
},

Usage

Let's save you've created a tweet like this:

import { Model } from 'lore-models';

const Tweet = Model.extend({
  urlRoot: 'http://localhost:1337/tweets'
})

const tweet = new Tweet()

The set() method can be used add additional attributes to the model, and there are two ways to call it.

The first is by providing a key/value pair, like this:

tweet.set('text', 'Some new tweet')

The second is by providing an object, like this:

tweet.set({
  text: 'Some new tweet'
})

In both cases, if you now examined the tweet.attributes property you would see this:

{
  id: 1,
  text: 'Some new tweet'
}

Most of the time, if you understand what it's doing, you could set the attributes directly, like this:

tweet.attributes = {
  id: 1,
  text: 'Some new tweet'
}

The reason you generally shouldn't, is because this method examines the attributes you provide, and if any of them match the idAttribute, it will set that property to the correct value. If you assign the attributes directly, this value may not set.