views:

45

answers:

3

I like jQuery's ability to method chain commands ( .animate().css() etc ) which in the backend is achieved by returning the special variable "this".

How can I implement a similar method of chaining without having to set state within my object. Take for example:

that.getHospitalCoverDataStore().findBy('short_name').withValue('sam');

This method chain queries a field in the datastore "short_name" using the value "sam". I can set an internal state to "short_name" when the first method has been called then look that up again when withValue is called. This seems like a kludge to me though, for a start I can't throw an error if withValue is called before findBy as it will reuse the last findBy setting.

How can I better implement this?

A: 

Looks like findBy() could be implemented as a separate object with the method withValue(), it doesn't look like withValue() should be a method for the HospitalCoverDataStore.

Andrew Dunn
+3  A: 

Your findBy method should return a separate object with a withValue method. (and perhaps startsWith, but no unrelated methods)

SLaks
+3  A: 

You can make the findBy method return a different object, that encapsulates the datastore and the field name, and that has the withValue method:

function findBy(field) {
  return {
    dataStore: this,
    field: field,
    withValue: function(value) {
      // query the dataStore and return result
    }
  };
}
Guffa
Love it, this is what I was thinking so it's good to get some confirmation on it.
Samuel