Custom Instance Behavior

Define your own instance methods

If you provide a methods field in the options passed to DS#defineResource or the DS constructor, JSData will wrap items of that resource (or of any resource if passing to the dS constructor) with a constructor function and add the functions defined on the methods field to the prototype of that constructor function. The methods option should be an object where the keys are method names and the values are functions. In this way you can add custom behavior to resource instances.

Instances come with a number of default instance methods that are shorthands for datastore methods that operate on individual items. See Instance Shorthands for more info.

Example:

var store = new JSData.DS({
  methods: {
    // global instance method
    foo: function () {
      return 'bar'; 
    }
  }
});

var User = store.defineResource({
  name: 'user',
  methods: {
    // resource-specific instance method
    fullName: function () {
      return this.first + ' ' + this.last;
    }
  }
});

var user = User.createInstance({ first: 'John', last: 'Anderson' });

user.foo(); // "bar"
user.fullName(); // "John Anderson"

user; // User { first: "John", last: "Anderson" }

Additional reading:

πŸ“˜

Need help?

Want more examples or have a question? Post on the Slack channel or mailing list then we'll get your question answered and probably update this wiki.